目录
0.头文件
#include<string>
1.本身属性
s.capacity(); //返回当前容量(不增加内存可存放元素个数)
s.size();//返回当前元素个数
s.length();//与size()相同,没有区别
s.empty();//字符串为空,返回true,非空,返回false
2.增加操作
s.append(str);//字符串尾端接上一个子串str
s.push_back(ch);//字符串尾端插入一个字符ch
s.insert(start,str);//在下标start处,插入str字符串
3.删除操作
s.erase(start,len);//删除下标start开始后的len长度子串
s.erase(start);//删除从下标start开始,之后所有的子串
s.clear();//此时调用size()或length(),都将返回0
s.pop_back();//字符串尾端弹出一个字符
4.修改字符串
s.replace(start,len,str);//从下标start开始后的len长度子串,替换为str
s.assign(str);//s内容被str替换
5.查找操作
s.find(str);//从字符串首查找str串在s中的位置,位置从0开始,若结果等于s.npos,则表示不存在
s.find(str,n);//从下标n开始查找
s.rfind(str);//从字符串尾部查找str在s中的位置
s.find_first_of(str);//str在字符串中第一次出现的位置
s.find_last_of(str);//str在字符串中最后一次出现的位置
注意:
s.find(str)也是返回第一次出现str的位置,与s.find_first_of(str)一样;
同理,s.rfind(str)与s.find_last_of(str)一样。
6.读取操作
s.substr(start,len);//返回下标start开始,len长度的子串(不会改变s),比如:s.substr(0,1),
//表示该字符串的第一个字符
7.遍历
如果直接输出字符串,可用
cout<<s.c_str();
(1)下标访问
string str = "hello";
int size = str.size();
for (int i = 0; i < size; i++)
cout << str[i];
或者
string str = "hello";
int i = 0;
for (int i=0; str[i] != '\0'; i++)
cout << str[i];
(2)使用iterator
string str = "hello";
string::iterator it = str.begin();
for (; it != str.end(); it++)
{
cout << *it;
}
8.其他
删除最后一个字符(三种)
s.erase(s.end()-1);
s.pop_pack();
s=s.substr(0,s.size()-1);
判断子串是否唯一存在字符串中
if( s.find(str)!=string::npos && s.find(str)==s.rfind(str))
{
//字符串中存在子串,并且前后找到的子串都在同一位置
}
int转string
int a=1;
string s=std::to_string(a);
string转int
string s="1";
int a=atoi(s.c_str());