C++字符串交换

C++字符串交换教程

C++ 中,我们需要交换两个 字符串 我们可以借助第三个中间 变量 过渡来实现,同时,C++ 提供了 swap 函数,可以直接实现交换两个字符串。

C++字符串交换swap详解

语法

s1.swap(s2);

参数

参数 描述
s1 要交换的字符串。
s2 要交换的字符串。

说明

我们使用了 swap 函数,实现了交换字符串 s1 和 s2。

案例

字符串交换

C++ 交换字符串

#include <iostream> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; string str1 = "Hello HaiCoder"; string str2 = "Hello World"; string temp; cout << "Before Str1 = " << str1 << ", Str2 = " << str2 << endl; temp = str1; str1 = str2; str2 = temp; cout << "After Str1 = " << str1 << ", Str2 = " << str2 << endl; }

程序运行后,控制台输出如下:

18_C字符串string交换swap.png

我们首先,定义了两个字符串 变量 str1 和 str2,接着,我们定义了一个临时变量 temp,最后,我们借助了中间变量 temp,实现了交换字符串 str1 和字符串 str2。

字符串交换

C++ 交换字符串

#include <iostream> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; string str1 = "Hello HaiCoder"; string str2 = "Hello World"; cout << "Before Str1 = " << str1 << ", Str2 = " << str2 << endl; str1.swap(str2); cout << "After Str1 = " << str1 << ", Str2 = " << str2 << endl; }

程序运行后,控制台输出如下:

19_C字符串string交换swap.png

我们可以直接借助字符串的 swap 函数,实现交换两个字符串变量。

C++字符串交换总结

在 C++ 中,我们需要交换两个字符串我们可以借助第三个中间变量过渡来实现,同时,C++ 提供了 swap 函数,可以直接实现交换两个字符串。