无涯教程-进程 - void swap(string& str)函数

54 阅读1分钟

此函数用于交换两个字符串对象的值。

swap - 语法

考虑两个字符串s1和s2,我们想交换这两个字符串对象的值。其语法为:

s1.swap(s2)

swap - 参数

它包含单个参数,该参数的值将与字符串对象的值交换。

swap - 返回值

它不返回任何值。

swap - 例子1

#include<iostream>
using namespace std;
int  main()
{
string r = "10";
string m = "20"
cout<<"Before  swap r contains " << r <<"rupees"<<
;
cout<<"Before  swap m contains " << m <<"rupees"<<
;
r.swap(m); 
cout<< "After  swap r contains " << r<<"rupees"<<
;
cout<< "After  swap m contains " << m<<"rupees";
return 0;
}

输出:

Before  swap  r  contains 10 rupees
Before  swap  m contains 20 rupees
After  swap r contains 20 rupees
After swap m contains 10 rupees

在此示例中,r和m是分别包含10和20卢比的两个字符串对象。我们使用交换函数交换那里的价值。交换后,r包含20卢比,m包含10卢比。

参考链接

www.learnfk.com/c++/cpp-str…