1. 截取子串
s.substr(pos, n) //截取s中从pos开始(包括0)的n个字符的子串,并返回
s.substr(pos) //截取s中从从pos开始(包括0)到末尾的所有字符的子串,并返回
2. 替换子串
s.replace(pos, n, s1) //用s1替换s中从pos开始(包括0)的n个字符的子串
3. 查找子串
s.find(s1) //查找s中第一次出现s1的位置,并返回(包括0)
s.rfind(s1) //查找s中最后次出现s1的位置,并返回(包括0)
s.find_first_of(s1) //查找在s1中任意一个字符在s中第一次出现的位置,并返回(包括0)
s.find_last_of(s1) //查找在s1中任意一个字符在s中最后一次出现的位置,并返回(包括0)
s.fin_first_not_of(s1) //查找s中第一个不属于s1中的字符的位置,并返回(包括0)
s.fin_last_not_of(s1) //查找s中最后一个不属于s1中的字符的位置,并返回(包括0)
一:find
函数原型:
size_t find ( const string& str, size_t pos = 0 ) const;
size_t find ( const char* s, size_t pos, size_t n ) const;
size_t find ( const char* s, size_t pos = 0 ) const;
size_t find ( char c, size_t pos = 0 ) const;
参数说明:pos查找起始位置 n待查找字符串的前n个字符
使用样例:
string str1("the usage of find can you use it");
string str2("the");
上面定义出了两个字符串;
str1.find(str2); // 从串str1中查找时str2,返回str2中首个字符在str1中的地址
str1.find(str2,5); // 从str1的第5个字符开始查找str2
str1.find("usage"); // 如果usage在str1中查找到,返回u在str1中的位置
str1.find("o"); // 查找字符o并返回地址
str1.find("of big",2,2); //从str1中的第二个字符开始查找of big的前两个字符
二:find_first_of
函数原型:
size_t find_first_of ( const string& str, size_t pos = 0 ) const;
size_t find_first_of ( const char* s, size_t pos, size_t n ) const;
size_t find_first_of ( const char* s, size_t pos = 0 ) const;
size_t find_first_of ( char c, size_t pos = 0 ) const;
参数和find基本相同,不再赘述!
特别注意:
find_first_of 函数最容易出错的地方是和find函数搞混。它最大的区别就是如果在一个字符串str1中查找另一个字符串str2,如果str1中含有str2中的任何字符,则就会查找成功,而find则不同;
比如:
string str1("I am change");
string str2("about");
int k=str1.find_first_of(str2); //k返回的值是about这5个字符中任何一个首次在str1中出现的位置;
代码示例:
#include<iostream>
#include<string>
using namespace std;
int main(){
string str1("hi,every one! I am heat_nan from dlut one");
string str2("heat_nan");
int k = str1.find(str2);
cout << "the position of 'heat_nan' is " << k << endl;
int k1 = str1.find("one");
cout << "the position of the first 'one' is " << k1 << endl;
int k2 = str1.find("one of", k1 + 1, 3);
cout << "the position of the second 'one' is " << k2 << endl;
int k3 = str1.find_first_of("aeiou");
while (k3 != string::npos){
str1[3] = '*';
k3 = str1.find_first_of("aeiou", k3 + 1);
}
cout << str1 << endl;
system("pause");
return 0;
}
输出结果:
the position of 'heat_nan' is 19
the position of the first 'one' is 9
the position of the second 'one' is 38
hi,*very one! I am heat_nan from dlut one
参考
https://www.cnblogs.com/catgatp/p/6407788.html
https://blog.csdn.net/iot_change/article/details/8496977
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2012-05-30 C++中结构体的的慨念和使用方法
2012-05-30 c++函数参数类型-引用、指针、值
2012-05-30 VS2008下编写调试dll的一个实例(参考msdn) .
2012-05-30 设置VS2008和IE8 调试ATL MFC ActiveX控件