用c++实现将两个字符串内容比较后交换内容输出
时间: 2024-05-10 19:19:25 浏览: 9
下面是一个简单的实现,在比较两个字符串内容后,如果字符串 1 的内容大于字符串 2 的内容,则交换两个字符串的内容,最后输出交换后的结果:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1, str2;
cout << "请输入字符串 1:";
cin >> str1;
cout << "请输入字符串 2:";
cin >> str2;
if (str1 > str2) {
string temp = str1;
str1 = str2;
str2 = temp;
}
cout << "交换后的结果为:" << endl;
cout << "字符串 1:" << str1 << endl;
cout << "字符串 2:" << str2 << endl;
return 0;
}
```
在这个程序中,我们通过 `string` 类型来表示字符串,并使用 `>` 运算符来比较两个字符串的内容大小。如果字符串 1 的内容大于字符串 2 的内容,则使用一个临时变量 `temp` 来交换两个字符串的内容。最后,我们输出交换后的结果。
相关问题
c++程序设计,本程序的功能是将两个字符串内容比较后交换内容输出
下面是一个简单的C++程序,实现了将两个字符串内容比较后交换内容输出的功能:
```
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1, str2;
cout << "请输入第一个字符串:";
cin >> str1;
cout << "请输入第二个字符串:";
cin >> str2;
if (str1 > str2) {
swap(str1, str2);
}
cout << "交换后的字符串为:" << str1 << " " << str2 << endl;
return 0;
}
```
程序中首先定义了两个字符串变量 str1 和 str2,并通过 cin 语句从用户输入中获取字符串的内容。
然后使用 if 语句比较两个字符串的内容,并在需要时使用 swap 函数交换两个字符串的值。
最后使用 cout 语句将交换后的字符串输出到屏幕上。
两个字符串交换内容c++
可以使用 std::swap() 函数来交换两个字符串的内容。示例代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "hello";
string str2 = "world";
cout << "Before swapping: " << endl;
cout << "str1 = " << str1 << endl;
cout << "str2 = " << str2 << endl;
swap(str1, str2);
cout << "After swapping: " << endl;
cout << "str1 = " << str1 << endl;
cout << "str2 = " << str2 << endl;
return 0;
}
```
输出结果:
```
Before swapping:
str1 = hello
str2 = world
After swapping:
str1 = world
str2 = hello
```