//刪除操做 erase #include<iostream> #include<string> using namespace std; int main() { string name( "AnnaLiviaPlurabelle" ); //生成字符串Annabelle typedef string::size_type size_type; //用一對迭代器iterator 做參數標記出要被刪除的字符的範圍 size_type start_pos = name.find_first_of('L'); size_type end_pos = name.find_last_of('a'); name.erase(name.begin()+start_pos,name.begin()+end_pos+1); cout<<name<<endl; return 0; }
程序2,插入操做ios
#include<iostream> #include<string> using namespace std; int main() { string love("I love you!"); string::size_type pos=love.find_first_of(' '); love.insert(pos," really"); //insert()操做也支持插入new_string的一個子部分 cout<<love<<endl; love+=' ';//追加空格 string new_string("It's funny."); string::size_type start_pos=new_string.find_first_of(' ');//要插入的字串開始位置 string::size_type length=3;//要插入的字串長度 love.insert(love.size(),new_string,start_pos+1,-1);//若是想插入從start_pos開始的整個子串,length值(變爲負) cout<<love<<endl; return 0; }
程序3.追加與賦值,交換,at()等操做app
#include<iostream> #include<string> using namespace std; int main() { string s1( "Mississippi" ); string s2( "Annabelle" ); string s3; //拷貝s1的前四個字符 s3.assign(s1,0,4); cout<<s3<<endl; s3+=' '; s3.append(s2,0,4);//追加s2的前四個字符到s3 cout<<s3<<endl; //交換兩個字符串對 s1.swap(s2); cout<<s1<<" "<<s2<<endl; //at函數提供了越界檢查 char t=s3.at(77);//此處應用try catch包括,之後會學到 cout<<t<<endl; return 0; }
程序4.replace操做
ide
#include<iostream> #include<string> using namespace std; int main() { string sentence("An ADT provides both interface and implementation." ); string::size_type position = sentence.find_last_of( 'A' ); string::size_type length = 3; // 用Abstract Data Type 代替ADT sentence.replace( position, length, "Abstract Data Type" ); cout<<sentence<<endl; //小練習 string quote1( "When lilacs last in the dooryard bloom" ); string quote2( "The child is father of the man" ); //用assign()和append()操做構造字符串The child is in the dooryard string quote3; string::size_type pos=quote2.find_first_of('f'); string::size_type start_pos=quote1.find_last_of('i'); string::size_type end_pos=quote1.find_last_of('b'); cout<<end_pos<<endl; quote3.assign(quote2,0,pos).append(quote1,start_pos,end_pos-start_pos); cout<<quote3<<endl; return 0; }
程序5.練習函數
實現下面的函數spa
string generate_salutation( string generic1, string lastname, string generic2, string::size_type pos, int length)code
#include<iostream> #include<string> using namespace std; string generate_salutation( string generic1, string lastname, string generic2, string::size_type pos, int length) { string::size_type position=generic1.find_last_of('D'); int len=5; string::size_type start_pos=generic1.find_first_of('M'); string::size_type end_pos=generic1.find_last_of(' '); //要用end_pos-start_pos計算得到要被替換的字串長度並做爲第二個參數傳入 generic1.replace(position,position+len,lastname).replace(start_pos,end_pos-start_pos,generic2,pos,length); return generic1; } int main() { string generic1( "Dear Ms Daisy:" ); string generic2( "MrsMsMissPeople" ); string result=generate_salutation(generic1,"Yangxiaoli",generic2,5,4); cout<<result<<endl; return 0; }