Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-04-15) 阅读数 9 #程序编程
文章标签 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的内容。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门