一下来介绍一下string容器函数的用法:
这里是一些增加和删除的函数
#includeusing namespace std; void test() { string str = "I"; str += " LOVE LOL"; str.insert(5,4,'a');//c语言字符串,在第五个位置,插入四个a cout << "str1= " << str << endl;// str.insert(5, "aaa");//c++风格字符串,在第五个位置开始插入三个a cout << "str2= " << str << endl; str.erase(5, 7);//从第五个位置开始删除7个字符 cout << "str3= " << str << endl; str.insert(5, str);//可以把定义好的变量名放入,运行时,插入的代码就是str,第五个位置插入str cout << "str4= " << str< 结果如下:
对于上面的" "当中的字符串,可以替换成字符串变量,但是' '却不可以替换成字符串变量。
以下是一些获取字符的函数:#includeusing namespace std; void test() { string str = "I "; str += "LOVE LOL LOL"; for (int i = 1; i < str.size(); i++)//通过size函数获得长度,通过[]的方式来获得(访问)字符 { cout << str[i] << " "; } cout << endl; for (int i = 1; i < str.size(); i++)//通过size函数获得长度,通过at函数的方式来获得(访问)字符 { cout << str.at(i) << " "; } cout << endl; str[0] = 'a';//也可通过[]进行修改,但是只能修改单个字符 cout << str << endl; str.at(1) = 'b';//也可通过at函数进行修改,但是只能修改单个字符 cout << str << endl; } int main() { test(); system("pause"); return 0; } 结果如下:
以下是assign函数的用法:#includeusing namespace std; #include void test() { string str1 = "hello world!"; cout << str1 << endl; string str2(str1); cout << str2 << endl; string str3; str3 = str2; cout << str3 << endl; string str4; str4.assign("hello c++"); cout << str4 << endl; string str5; str5.assign("hello c++", 5);//输出为hello cout << str5 << endl; string str6; str6.assign(str5); cout << str6 << endl; string str7; str7.assign(10, 'a'); cout << str7 << endl; } int main() { test(); system("pause"); return 0; } 结果如下:
assign函数主要的作用是赋值,其用法和作用相当简单
以下是append函数的用法:#includeusing namespace std; void test() { string str = "我"; str += "爱玩游戏"; cout << "str=" << str << endl; string str2 = "loll"; str += str2; cout << "str=" << str << endl; string str3 = "I "; str3.append("love "); //str3 += str2; //str3.append(str2); //cout << str3 << endl; str3.append("lol bbbb cccc", 3); cout << str3 << endl; //string str4; //tr3.append("aaa bbbb cccc", 3); str3.append(str2, 0, 3);//参数2,从哪个位置开始截至,参数3,截取几个位数 cout << str3 << endl; } int main() { test(); system("pause"); return 0; } 结果如下:
append函数主要是起添加作用总结:无论是添加字符还是删除字符还是其他函数,参数添加还是计算字符位置,下标都是从0开始索引,切记!切记!切记!!!



