How to swap the content of two strings in C++?

To exchange the contents of two strings, you can use the standard library function std::swap in C++.

The example code is shown below:

#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;
}

Run Output:

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

In the above example, we used the std::swap function to switch the contents of str1 and str2.

bannerAds