基本使用方法
一、输入
string s;
cin >> s;
getline(cin, s) ; //使用默认的' '作为终止符 getline(cin, s, '!') ; //以'!'作为终止符
二、复制
string s1 = "hello World" ; string s2 = s1 ; //"hello World" 复制, string s3(s1); //"hello World" 拷贝构造函数, string s4(s1, 2); //"llo World" 将s1的第2个位置到末尾当作字符串的初值 string s5(s1, 3, 5); //"lo Wo" 将s1的第2个位置开始的5个字符作为字符串的初值 string s8(5, 'a'); //“aaaaa” 生成一个字符串,包含5个c字符
三、连接
string s1 = "Hello" ; string s2 = "World" ;string s3, s4; s1 += s2 ; //"HelloWorld" 连接 s3 = string("aaa") + "bbb"; //"aaabbb" s4 = "aaa" + "bbb"; //错误, 必须转成string类型!!!!!
四、比较
string s1 = "hello" ; string s2 = "world" ; if(s1 < s2) cout<<"s1 < s2" ; //比较
五、倒置串
string s = "hello" ; reverse(s.begin(), s.end()) ; //需要包含algorithm头文件, #include<algorithm>
六、查找串
string s1 = "hhhelloworlddd" ; //位置从0 ~ 9 s1.find("w") ; // 7 找第1个w的位置 s1.find("w", 10) ; // -1 从第10个位置开始找w s1.find_first_of("o"); //6 找第1次出现"o"的位置 s1.find_first_of("o",7); //8 从s1的第7个位置开始查找 s1.find_first_not_of("h"); //3 找第1个不是"h"的字符的位置 s1.find_last_of("o"); //8 //从后面开始找"o" s1.find_last_of("o", 7); //6 //从后面7个字符中找"o"出现的位置 s1.find_last_not_of("d"); //10
七、替换和字串
string s1,s2,s3; s1 = "hello world!" ;
s2 = s1.substr(3, 5); //"lo wo" 从第3个位置开始,往后5个字符 s3 = s1.substr(6); //"world!" 从第6个字符到末尾部分 s1.replace(2, 5, "tt"); //"hettorld" 从第2个位置,往后5个字符换成“tt”
八、修改字符串
①. append - 追加
string s = "hello" ;
s.append("world") ; //将"world"追加到s中
②. push_back - 追加字符到字符串
string s = "hello" ;
s.push_back('!') ; //将'!'追加字符到字符串s中
③. insert - 插入
string s = "hello" ;
s.insert(2, "www") ; //将字符串"www"插入到字符串s中, 插入位置为2
④. erase - 从字符串中擦除一些字符
string s = "hello" ;
s.erase(1, 2) ; //从下标为1处向后擦去2个字符
⑤. swap - 与另一字符串交换内容
string s1 = "hello" ;
string s2 = "world" ;
s1.swap(s2) ; //将s1与s2中的字符串进行交换
九、获取字符串状态
s.size() //返回字符串大小 s.length() //返回字符串长度 s.max_size() //返回字符串最大长度 s.clear() //清空字符串 s.empty() //判断字符串是否为空
十、string中的所有s1都替换成s2
#include <iostream> #include <string> using namespace std; //"12212"这个字符串的所有"12"都替换成"21" string& replace_all( string str, const string& old_value, const string& new_value ) //替换为22211 { while( true ) { string::size_type pos( 0 ); if( ( pos = str.find( old_value ) ) != string::npos ) { str.replace( pos, old_value.length(), new_value ); } else { break; } } return str; } string& replace_all_distinct( string str, const string& old_value, const string& new_value ) //替换为21221 { for( string::size_type pos( 0 ); pos != string::npos; pos += new_value.length() ) { if( ( pos = str.find( old_value, pos ) ) != string::npos ) { str.replace( pos, old_value.length(), new_value ); } else { break; } } return str; } int main() { cout << replace_all( string("12212"), "12", "21" ) << endl; //22211 cout << replace_all_distinct( string("12212"), "12", "21" ) << endl; //21221 }