String是C语言char数组的变形和封装,作为一个结构体存在,具有许多集成的操作,包括初始化、插入、删除、清空、计数、判断是否空等
一、string建立
#include<string>
#include<iostream>
using namespace std;
int main()
{
string s1;//创建空string
string s2("How are you");//用字符串构造函数初始化
string s3(s2);//复制构造函数
string s4(s2,0,3);//取已定义字符串的部分作为初始对象
string s5="Fine";//赋值类型的初始化
string s6=s2+"Fine";//用已定义的字符串的连接后作为初始化内容
string s7="How are you";
string s8(s8.begin(),s8.end());
string s9(s8.begin(),s8.end());
string s10(s8.begin()+3,s8.end()-1);
cout<<s1<<endl;
cout<<s2<<endl;
cout<<s3<<endl;
cout<<s4<<endl;
cout<<s5<<endl;
cout<<s6<<endl;
cout<<s7<<endl;
cout<<s8<<endl;
cout<<s9<<endl;
cout<<s10<<endl;
system("pause");
}
二、插入
#include<string>
#include<iostream>
using namespace std;
int main()
{
string s1="do";
cout<<"s1 size\t"<<s1.size()<<endl;
s1.insert(2," you");//insert插入 指定位置
s1.append(" know");//在string后面插入 ,append()
s1=s1+" my heart";//连接插入
cout<<"total size\t"<<s1.size()<<endl;
cout<<s1<<endl;
system("pause");
}
三、string的部分替换
#include<string>
#include<iostream>
using namespace std;
int main()
{
string s="what's your name?";
cout<<"原来的字符串"<<s<<endl;
s.replace(7,4,"her");//7替换位置,替换掉的字符长度,her替换内容
cout<<"替换过的字符串"<<endl;
cout<<s<<endl;
system("pause");
}
四、查找
#include<string>
#include<iostream>
using namespace std;
int main()
{
string s="What's your name?my name is TOM.How do you do?Fine,thanks. ";
int n=s.find("you");//从开始找到的第一个you位置
cout<<"the first pos of you is "<<n<<endl;
n=s.find("you",15);//从15这个位置开始查找的第一个you的位置
cout<<"从15开始找到的you位置 "<<n<<endl;
n=s.find_first_of("abcde");//找到s中第一个在字符串abcde中字符的位置
cout<<"The first pos of abcde is "<<n<<endl;
n=s.find_first_of("abcde",3);//从第三个位置开始找到的第一个在abcde中的位置
cout<<"find pos of abcde from 2 "<<n<<endl;
n=s.find_first_not_of("quert");//找到的第一个不在quert中的字符的位置
cout<<"not find in quert "<<n<<endl;
n=s.rfind("you");//从字符尾部开始找到的第一个you的y的位置
cout<<"从后往前找的第一个you"<<n<<endl;
system("pause");
}
五、删除(erase())
# include<iostream>
#include<string>
using namespace std;
int main()
{
string s1="How are you?";
s1.erase(s1.begin(),s1.begin()+3);
cout<<"删除后的s1"<<s1<<endl;
string s2="Thanks!";
s2.erase(s2.begin(),s2.end());
cout<<"删除后的s2"<<s2<<endl;
system("pause");
return 0;
}
六、比较和反转
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string s1="this";
string s2="that";
if(s1>s2)cout<<"s1>s2";//重载过的><==
else if(s1<s2)cout<<"s1<s2";
else cout<<"s1=s2";
cout<<endl;
reverse(s1.begin(),s1.end());//反转函数
reverse(s2.begin(),s2.end());
cout<<"翻转后"<<endl;
if(s1>s2)cout<<"s1>s2";
else if(s1<s2)cout<<"s1<s2";
else cout<<"s1=s2";
cout<<endl;
system("pause");
}