两个字符串交换内容c++
时间: 2023-12-24 15:01:54 浏览: 39
可以使用 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
```
相关问题
交换两个字符串内容的函数方法c++
可以使用以下代码交换两个字符串的内容:
```c++
#include <iostream>
#include <string>
using namespace std;
void swapString(string& str1, string& str2) {
string temp = str1;
str1 = str2;
str2 = temp;
}
int main() {
string str1 = "hello";
string str2 = "world";
cout << "Before swapping: " << endl;
cout << "str1: " << str1 << endl;
cout << "str2: " << str2 << endl;
swapString(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
```
在这个例子中,我们定义了一个名为 `swapString` 的函数,该函数接受两个字符串的引用作为参数。函数内部定义了一个 `temp` 字符串,将 `str1` 的值复制给 `temp`,然后将 `str2` 的值赋给 `str1`,最后将 `temp` 的值赋给 `str2`,完成了两个字符串的内容交换。
用c++实现将两个字符串内容比较后交换内容输出
下面是一个简单的实现,在比较两个字符串内容后,如果字符串 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` 来交换两个字符串的内容。最后,我们输出交换后的结果。