一、头文件
#include<string>
二、初始化
有两种方式,使用等号的是拷贝初始化,不使用等号的是直接初始化
1)string str1="hello world";
2)string str2("hello world");
3)string str3=str1;
4)string str4(str2);
5)string str5(10,'a');
三、常用操作
1)获取长度
str.length();
str.size();//均可以,不包括'\0'
2)反转字符串
reverse(str.begin(),str.end());
3)查找,判断子串
str.find(str1);//返回的是str1在str中第一次出先的位置,如果失败,返回string::npos
如下:
string a="abc";
string b="123";
string::size_type idx;
idx=a.find(b);
if(idx==string::npos)
cout<<"not found"<<endl;
4)数值转化
string str=to_string(val);//把val转化成string
int num=stoi(str,p,b);//把字符串s从p处开始转化为b进制的int
long num=stol(str,p,b);//把字符串s从p处开始转化为b进制的long
unsigned long num=stoul(str,p,b);//把字符串s从p处开始转化为b进制的unsigned long
long long num=stoll(s,p,b);//把字符串s从p处开始转化为b进制的long long
unsigned long long num=stoull(s,p,b);//把字符串s从p处开始转化为b进制的unsigned long long
flaot num=stof(s,p);//把字符串s从p处开始转为float
double num=stod(s,p);//把字符串从p处开始转化为double
long double num=stold(s,p);//把字符串s从p处开始转为long double
5)复制子串
string str=s.substr(i,j);//从字符串s的第i位开始长度为j的字符串复制给str
string str=s.substr(i);//将字符串s从i开始到结束复制给str
6)判断空
s.empty();//判断字符串是否为空
7)清空
s.clear();//删除全部字符
8)字符串比较大小
9)find函数
10)调整字符串大小
s.resize(num);//重新调整字符串的大小为count
如s="abcd"
s.resize(2);//字符串变短,现在只有2个字符
s.resize(6,'b');//字符串变长,则需要为多余的赋值,此时字符串为abcdbb