string是C++标准库中的类,掌握后会让编程事有半功倍的效果,使用时要包含头文件#include< string >,加上using namespace std;
下面介绍string中常见的一些用法:
1.查找
int a.find(str,pos);
从a字符串中查找str字符串,从pos位置开始查找,
返回值=str字符串第一次出现的位置
如果没有找到返回值为-1;
#include<iostream>
#include<string>
using namespace std;
int main(){
string a="abcdefg";
cout<<a.find("cd",0);<<endl;
return 0;
}
2.替换
a.place(i,n,str);
a字符串从i开始替换n个字符为字符串str
(可以理解为n个字符直接删掉,将str字符串插入)
注意:a的值会改变为替换后的
返回值=替换后的字符串
#include<iostream>
#include<string>
using namespace std;
int main(){
string a="xxxoooxxx";
cout<<a.replace(3,3,"xxx")<<endl;
return 0;
}
3.获取字符串长度
length(),size();
返回值=字符串的长度
#include<iostream>
#include<string>
using namespace std;
int main(){
string a="xxxoooxxx";
cout<<a.length()<<endl;
cout<<a.size()<<endl;
return 0;
}
4.判空
a.empty();
空返回=1,非空返回=0;
#include<iostream>
#include<string>
using namespace std;
int main(){
string a="xxxoooxxx";
string b;
cout<<a.empty()<<endl;
cout<<b.empty()<<endl;
return 0;
}
5.插入字符串
str1.insert(n,str2)
从str1的n位置插入str2字符串
返回值=插入后的字符
#include<iostream>
#include<string>
using namespace std;
int main(){
string a="xxxoooxxx";
string b="ttt";
cout<<a.insert(3,b)<<endl;
return 0;
}
拓展:
string s1=“hello”;
s1.insert(1.“ins”);//从s1的位置1开始,插入"ins"字符串,即s1=“hinsello”;
s1.insert(1,“ins”,2)//从s1的位置1 开始,插入"ins"字符串的前两个字符,即s1="hinello;
s1.insert(1,“ins”,1,2)//从s1的1位置开始,插入"ins"字符串从1位置开始的2个字符,即s1=“hnsello”;
6.删除字符串
str.erase(n,m)
删除str字符串从n开始的m个字符
返回值=删除后的字符串
#include<iostream>
#include<string>
using namespace std;
int main(){
string a="xxxoooxxx";
string b="ooo";
cout<<a.erase(3,3)<<endl;
return 0;
}
7.截图字符串字段
str.substr(a,b);
截取字符串a位置到b位置
返回值=截取的字段
注意:不会改变原来的字符串
#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
int main(){
string str="abcdf";
cout<<str.substr(1,3)<<endl;
cout<<str<<endl;
return 0;
}