租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

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

发布时间:2024-01-06 00:23:23

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

要交换两个字符串的内容,可使用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的内容。