前边说的都是string类的构造函数
下面这些是用于string操作的库函数
substr()//主要功能是复制子字符串,要求从指定位置开始,并具有指定的长度。
append() //方法在被选元素的结尾(仍然在内部)插入指定内容。提示:如需在被选元素的开头插入内容,请使用prepend()方法。
replace()//该函数返回一个字符串,其中指定的字符串已经被替换为另一字符串,并且替换的次数也可以指定。
代码实例:
#include <iostream>
#include <string>
using namespace std;
//20200425 测试字符串操作 公众号:C与C语言plus
int main()
{
string s("Hello world");
string s2 = s.substr(6,5); //从第6个开始取5个
cout << s2 << endl ; //s2为world
s2 = s.substr(6); //从第6个开始取复制所有的
cout << s2 << endl ; //s2为world
s2 = s.substr(6); //s2复制s,相当于s2=s
cout << s2 << endl ; //s2为Hello world
s = "C++ Primer";
s.append(" 3rd Ed"); //再s最后添加3rd Ed
cout << s<< endl ; //s为C++ Primer 3rd Ed
s = "C++ Primer";
s.insert(s.size()," 3rd Ed"); //最后插入
cout << s<< endl ; //s为C++ Primer 3rd Ed
s.replace(11,3,"4th"); //下标11开始3个替换4th
cout << s<< endl ; //s为C++ Primer 4th Ed
s.replace(11,3,"Fourth"); //下标11开始3个替换Fourth
cout << s<< endl ; //s为C++ Primer Fourth Ed
s = "C++ Primer 3rd Ed"; //replace相当于先删除后插入
s.erase (11,3); //删除3rd
s.insert(11,"Fourth"); //插入Fourth
cout << s<< endl ; //s为C++ Primer Fourth Ed
return 0;
}