C++ string 类常用接口解析(附代码介绍)
在 C++ 编程中,std::string是处理字符串最常用的工具,它封装了底层的字符数组操作,提供了丰富且易用的接口,相比 C 语言的字符数组,安全性和便捷性都大幅提升。
一、string 类基础(初始化与赋值)
1. 初始化方式
string类支持多种初始化方式,满足不同场景的需求:
#include <iostream> #include <string> using namespace std; int main() { // 1. 空字符串初始化 string s1; // 2. 用C风格字符串初始化 string s2 = "hello world"; // 3. 用指定字符重复n次初始化 string s3(5, 'a'); // 结果:"aaaaa" // 4. 拷贝初始化 string s4 = s2; // 5. 截取其他string的部分字符初始化(从下标3开始,取4个字符) string s5(s2, 3, 4); // 结果:"lo w" cout << "s1: " << s1 << endl; cout << "s2: " << s2 << endl; cout << "s3: " << s3 << endl; cout << "s4: " << s4 << endl; cout << "s5: " << s5 << endl; return 0; }2. 赋值接口
除了初始化时赋值,还可以通过=或assign接口修改字符串:
int main() { string s; // 1. 直接赋值 s = "hello"; cout << "赋值后s: " << s << endl; // 2. assign赋值(支持更灵活的赋值方式) s.assign("world", 3); // 取前3个字符:"wor" cout << "assign后s: " << s << endl; // 3. 用其他string的部分赋值 string s2 = "123456"; s.assign(s2, 2, 3); // 从下标2开始取3个:"345" cout << "assign部分字符后s: " << s << endl; return 0; }二、字符串长度与容量操作
1. 核心接口
| 接口 | 功能说明 |
|---|---|
size() | 返回字符串有效字符个数(无符号) |
length() | 与 size () 功能相同 |
empty() | 判断字符串是否为空,空返回 true |
capacity() | 返回当前字符串分配的存储空间大小 |
resize() | 调整字符串有效字符个数 |
reserve() | 预留存储空间(不改变有效字符) |
2. 代码演示
int main() { string s = "hello"; cout << "有效字符数(size): " << s.size() << endl; // 输出5 cout << "有效字符数(length): " << s.length() << endl;// 输出5 cout << "是否为空(empty): " << boolalpha << s.empty() << endl; // 输出false cout << "当前容量(capacity): " << s.capacity() << endl; // 不同编译器结果不同,如15 // resize:有效字符数调整为8,不足补'\0' s.resize(8); cout << "resize后size: " << s.size() << endl; // 输出8 cout << "resize后内容: " << s << endl; // 输出hello // reserve:预留20个字符的空间,不改变有效字符 s.reserve(20); cout << "reserve后capacity: " << s.capacity() << endl; // 输出20 cout << "reserve后size: " << s.size() << endl; // 仍为8 return 0; }三、字符串访问与修改
1. 访问方式
[]:直接访问指定下标字符(无越界检查)at():访问指定下标字符(有越界检查,抛异常)front():访问第一个字符back():访问最后一个字符
2. 修改接口
push_back():尾部追加单个字符append():尾部追加字符串(支持多种格式)+=:尾部追加字符 / 字符串(最常用)insert():指定位置插入字符 / 字符串erase():删除指定位置的字符
3. 代码演示
int main() { string s = "hello"; // 访问字符 cout << "下标1的字符([]): " << s[1] << endl; // 输出e cout << "下标1的字符(at): " << s.at(1) << endl; // 输出e cout << "第一个字符(front): " << s.front() << endl;// 输出h cout << "最后一个字符(back): " << s.back() << endl;// 输出o // 修改字符 s[1] = 'E'; cout << "修改后s: " << s << endl; // 输出hEllo // 尾部追加 s.push_back('!'); cout << "push_back后: " << s << endl; // 输出hEllo! s += " world"; cout << "+=后: " << s << endl; // 输出hEllo! world s.append(3, '*'); cout << "append后: " << s << endl; // 输出hEllo! world*** // 插入:在下标6的位置插入"new " s.insert(6, "new "); cout << "insert后: " << s << endl; // 输出hEllo! new world*** // 删除:从下标6开始删除4个字符("new ") s.erase(6, 4); cout << "erase后: " << s << endl; // 输出hEllo! world*** return 0; }四、字符串查找与替换
1. 核心接口
| 接口 | 功能说明 |
|---|---|
find() | 从左往右查找子串 / 字符,返回首次出现的下标 |
rfind() | 从右往左查找子串 / 字符,返回首次出现的下标 |
replace() | 替换指定位置的子串 |
2. 代码演示
int main() { string s = "hello world, hello c++"; // 查找子串"hello" size_t pos = s.find("hello"); if (pos != string::npos) { // string::npos表示未找到 cout << "hello首次出现的位置: " << pos << endl; // 输出0 } // 从下标6开始查找"hello" pos = s.find("hello", 6); cout << "hello第二次出现的位置: " << pos << endl; // 输出13 // 从右往左查找"hello" pos = s.rfind("hello"); cout << "hello最后出现的位置: " << pos << endl; // 输出13 // 替换:将第一个hello替换为HELLO s.replace(0, 5, "HELLO"); cout << "replace后s: " << s << endl; // 输出HELLO world, hello c++ return 0; }五、字符串拼接与比较
1. 拼接
除了前面的+=、append,还可以用string::operator+直接拼接两个字符串:
string s1 = "hello"; string s2 = "world"; string s3 = s1 + " " + s2; // 结果:"hello world"2. 比较
string重载了比较运算符(==、!=、<、>、<=、>=),按ASCII 码值逐字符比较;也可以用compare()接口,返回值规则:
- 0:两字符串相等
- 正数:当前字符串更大
- 负数:当前字符串更小
int main() { string s1 = "apple"; string s2 = "banana"; string s3 = "apple"; // 运算符比较 cout << (s1 == s3) << endl; // true cout << (s1 < s2) << endl; // true(a的ASCII小于b) // compare接口 int ret = s1.compare(s2); cout << "s1.compare(s2): " << ret << endl; // 负数(s1 < s2) ret = s2.compare(s1); cout << "s2.compare(s1): " << ret << endl; // 正数(s2 > s1) return 0; }六、其他常用接口
1. 转换与截取
c_str():将 string 转为 C 风格字符串(const char*),常用于兼容 C 语言接口substr(pos, n):截取从 pos 开始的 n 个字符,返回新 string
2. 代码演示
int main() { string s = "hello world"; // 转为C风格字符串 const char* cstr = s.c_str(); cout << "C风格字符串: " << cstr << endl; // 输出hello world // 截取子串:从下标6开始取5个字符 string sub = s.substr(6, 5); cout << "截取的子串: " << sub << endl; // 输出world return 0; }总结
string类封装了字符数组的底层操作,核心接口覆盖初始化、长度 / 容量、访问 / 修改、查找 / 替换、比较 / 拼接等场景,是 C++ 处理字符串的首选;- 优先使用
size()而非length()(语义更清晰),[]访问字符需注意越界,at()会抛异常更安全; - 常用追加方式:
+=(简洁)、push_back()(单个字符)、append()(复杂场景);查找失败需判断string::npos。
