In this C++ tutorial, you will learn how to swap string values between two string variables using string::swap() function, with examples.
Swap Strings
string::swap() function swaps the value of this string with the given string.
Syntax
The syntax to swap string values between the string variables str1
and str2
is
str1.swap(str2)
Examples
1 Swap string values between string variables str1 and str2
In the following program, we take two strings: str1
and str2
with initial values, and swap their values between them using string::swap()
function.
C++ Program
#include <iostream> using namespace std; int main() { string str1 = "apple"; string str2 = "mango"; str1.swap(str2); cout << str1 << endl; cout << str2 << endl; }
Output
mango apple Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned how to swap values between two strings using string::swap() function, with examples.