目录
string是C++ STL中常见的内置数据结构。不用再像C语言那样用char*,string更方便,不用再时刻关注字符串最后的空字符。
1.初始化
string s1 = "alibli"; // 初始化,除了最后的空字符外其他都拷贝到s1中
string s2 = s1;
string s3(s1);
string s4(6,'a'); // "aaaaaa"
string s5(s1, 3); // "bli"
string s6(s1, 3, 2); // "bl"
string s7(s1.begin(), s1.end());
2.增
后面增一个字符串,最常用+=,也可用append()
string s1 = "ali";
s1 += "cli"; // 变为alibli
s1.append("123"); // 变为alibli123
s1.append("456", 2); // 只增2个字符,变为alibli12345
s1.append("789", 0, 2); // 从0开始2个,注意2是个数,变为alibli1234578
后面增一个字符,push_back()
string s1 = "ali";
s1.push_back('6'); // 变为ali6
中间插入字符串或字符
string s1("ali");
s1.insert(0, "love"); // loveali
s1.insert(0, 2, '0'); // 在指定位置插入2个'0' 00loveali
s1.insert(s1.begin(), 3, 'b'); // 迭代器指定位置插入3个'b' bbb00loveali
3.删
删最后一个字符用pop_back()
删中间几个字符用erase()
string s1("alibli");
s1.erase(3, 2); // 从s1[3]开始删除两个 alii
s1.erase(2); // 从s1[2]开始删到末尾 al
清空用clear()
取子串用substr()
string s1("alibli");
string s2 = s1.substr(3, 2); // bl
string s3 = s1.substr(3); // bli
4.查
用find(),里面字符或字符串均可。
string s1("alibli");
cout << s1.find('b') << endl; // 不存在返回string::npos,-1,存在返回idx 3
cout << s1.find("bl") << endl; // 匹配查找字符串的位置 3
cout << s1.find("li", 3) << endl; //从指定位置开始匹配 4
cout << s1.find_first_of('i') << endl; // 2
cout << s1.find_last_of("li") << endl; // 5
cout << s1.find_first_not_of("al") << endl; // 2
cout << s1.find_last_not_of("li") << endl; // 3
5.改
用replace()
string s1("alibli");
s1.replace(3, 2, "123"); // [3,5)替换为“123”,2个字符换为3个字符 ali123i
s1 = "alibli";
s1.replace(3, 2, "123", 2); // 2换2 ali12i
s1 = "alibli";
s1.replace(3, 2, "456", 1, 2); // 2换2 ali56i
6.格式转换
转int用stoi()
转float用stof()
数字转string用to_string()
string s1("123");
cout << stoi(s1) << endl; // 转为整数
cout << stof(string("12.3")) << endl; // 转为浮点型
cout << to_string(124) << endl; // 数字转为字符串
cout << to_string(12.4) << endl;
划重点
注意一旦出现两个数字,一般第二个表示个数n个,并不是终止下标。