string常用函数用法集合

写在前面的话:

我的字符串还是太弱了,记录一下string类型实用的一些函数用法。

(1)find()

定义string 类型的 s和t

1.s.find(t):从s中找t,返回找到的第一个t的第一个字母的下标.没有找到返回-1.

int pos =s.find(t);

2.s.find(t,p):从下标p开始,从s中查找字符串t,返回值同上。

num=-1;
while(1){
num++;
pos=s.find(t,num);
if(...)break;
}

(2)replace()

定义string 类型的 s和t

2.s.replace(s.begin(),s.begin()+len,t):用t替换s起始位置从s.begin()开始到s.begin()+6位置的字符。

string s,t;
    cin>>s>>t;
    s.replace(s.begin(),s.begin()+t.size(),t);
    cout<<s;

2.s.replace(pos,len,t);用t替换从指定位置pos开始长度为len的字符串

输入:aaddaa qwe
string s,t;
    cin>>s>>t;
    s.replace(0,3,t);
    cout<<s;

len不一定要是t的长度。

猜你喜欢

转载自www.cnblogs.com/sky-zxz/p/9748253.html