string常用库函数
YanSS_0416
·
2024-06-03 11:30:44
·
个人记录
string的库函数非常多,若全部掌握十分浪费时间,我们只需要掌握常用的重要库函数即可,如有需要,可以上C++标准函数库查阅。
一、常用操作
1.比较与连接
比较:>、>=、<、<=、!=
连接:+、+=
示例代码:
string s,t;
s="hello";
t="world";
cout<
输出结果:
2.size/length
功能:求字符串长度
3.begin/end
功能:指向字符串第一个字符/最后一个字符
二、其他常用库函数
1.insert
功能:在指定位置插入字符串/字符
代码示例:
string s;
s="helloworld";
s.insert(5,"C++");
cout<
//在下标为5的位置,插入字符串C++
s.insert(5,3,'y');
//在下标为5的位置,插入3个字符y
cout<
输出结果:
2.erase
功能:删除字符
代码示例:
string s;
s="helloworld";
s.erase(3,2);
cout<
//从下标为3的位置开始,删除2个字符
s.erase(3);
cout<
//从下标为3的位置开始,删除全部字符
s.erase();
cout<
//删除整个字符串
输出结果:
3.swap
功能:交换字符串
代码示例:
string s,t;
s="hello";
t="world";
s.swap(t);
cout<
输出结果:
4.find/rfind
功能:查找字符串/字符,并返回它的下标(若没有找到则返回-1)
代码示例:
string s;
int pos;
s="helloworld";
pos=s.find('o');
cout< //在s中查找字符o,并返回它在s中的下标 pos=s.find("world"); cout< //在s中查找字符串world,并返回第一个字符的下标 pos=s.rfind('o'); cout< //反方向在s中查找字符o,并返回它在s中的下标 输出结果: 5.substr 功能:从指定位置取出指定数量的字符 代码示例: string s,t; s="helloworld"; t=s.substr(5,3); cout< //从下标为5的位置取出3个字符 t=s.substr(5); cout< //从下标为5的位置取出字符,全部取完 输出结果: 6.replace 功能:从指定位置替换为其他字符 代码示例: string s,t; s="helloworld"; s.replace(2,2,"e"); cout< //将下标为4的后两个字符均替换为字符e t="123"; s.replace(1,3,t); cout< //将下标为1的后三个字符均替换为字符串t 输出结果: