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");
}