温馨提示×

c++如何交换两个字符串的内容

c++
小亿
138
2024-01-06 00:23:23
栏目: 编程语言

要交换两个字符串的内容,可以使用C++的标准库函数std::swap

示例代码如下:

#include <iostream>
#include <string>

int main()
{
    std::string str1 = "Hello";
    std::string str2 = "World";

    std::cout << "交换前:" << str1 << " " << str2 << std::endl;

    std::swap(str1, str2);

    std::cout << "交换后:" << str1 << " " << str2 << std::endl;

    return 0;
}

运行结果:

交换前:Hello World
交换后:World Hello

在上面的例子中,我们使用std::swap函数交换了str1str2的内容。

0