目录
String类
string是c++风格的字符串,实际上string本质上是一个类
string类内部封装了很多成员方法。
使用string类时必须在程序的最开头包含头文件:#include<string>
string构造函数
string s1; //默认构造
const char* str="hello";
string s2(str); //使用字符串进行初始化
cout<<"s2:"<<s2<<endl;
//拷贝构造
string s3(s2); //使用一个string对象初始化另一个string对象
cout<<"s3:"<<s3<<endl;
string赋值操作
string str1;
str1="hello"; //使用char*类型字符串赋给当前字符串
cout<<"str1="<<str1<<endl;
string str2;
str2=str1; //将字符串赋给另一个字符串
cout<<"str2="<<str2<<endl;
string str3;
str3='a'; //把字符赋给字符串
cout<<"str3="<<str3<<endl;
string str4;
str4.assign("hello"); //把字符串hello赋给当前字符串
cout<<"str4="<<str4<<endl;
string str5;
str5.assign("hello world",5); // 把字符串的前5个字符赋给当前字符串
cout<<"str5="<<str5<<endl;
string str6;
str6.assign(8,'a'); //用8个字符a赋给当前字符串
cout<<"str6="<<str6<<endl;
string字符串拼接
string str1="hello";
str1+="world"; //重载+=操作符
cout<<"str1="<<str1<<endl;
string str2="I love ";
str2.append("c++");
cout<<"str2="<<str2<<endl;
str2.append("c++",1); //将字符串的前1个字串添加到末尾
cout<<"str2="<<str2<<endl;
string str3="hello world";
string str4;
str4.append(str3,0,5); //从第0个字符截取,截取个数为5
cout<<"str4="<<str4<<endl;
string查找和替换
//查找
string str1="abcdefag";
int pos=str1.find("de"); //返回值为int,查找时从索引0开始查找
cout<<pos<<endl;
int pos1=str1.find("t"); //没有找到返回-1
cout<<pos1<<endl;
int pos3=str1.rfind("a"); //注意rfind()是查找字符串最后一次出现的位置(从右向左查找)
cout<<pos3<<endl;
//替换
string str2="hello";
str2.replace(1,3,"000"); //从索引1开始3个字符替换为000
cout<<"str2="<<str2<<endl;
string字符串比较
//字符串比较
string str1="aello";
string str2="hello";
//使用compare()函数比较字符串方法时,返回的值为0,1和-1
int a=str1.compare(str2);
cout<<a<<endl;
if(str1.compare(str2)==0)
{
cout<<"str1等于str2"<<endl;
}
else if(str1.compare(str2)>0)
{
cout<<"str1大于str2"<<endl;
}
else
{
cout<<"str1小于str2"<<endl;
}
string字符存取
//string字符存取
string str="hello";
//通过[]访问单个字符
for(int i=0;i<str.size();i++)
{
cout<<str[i]<<endl;
}
//通过at()访问单个字符
for(int i=0;i<str.size();i++)
{
cout<<str.at(i)<<endl;
}
//修改单个字符
str[0]='k';
cout<<str<<endl;
str.at(0)='p';
cout<<str<<endl;
string插入和删除
string str="hello";
//插入
str.insert(1,"00"); //在索引1位置插入字符串00
cout<<str<<endl;
//删除
str.erase(1,2);
cout<<str<<endl;
string子串
//截取子串
string str="abcdef";
string subStr=str.substr(1,3);
cout<<subStr<<endl;