【数据结构】字符串操作整理(C++)
1. 字符串长度与容量
size()
/ length()
- 定义:返回字符串的当前长度(字符数)。
- 用法:
string s = "hello"; cout << s.size(); // 输出:5
- 提示:
size()
和length()
功能完全相同,可互换使用。
capacity()
- 定义:返回当前分配给字符串的内存容量(字符数)。
- 用法:
string s = "hello"; cout << s.capacity(); // 可能输出:15(取决于编译器实现)
- 提示:容量通常大于实际长度,以避免频繁重新分配内存。
2. 字符串修改
push_back(char c)
- 定义:在字符串末尾添加一个字符。
- 用法:
string s = "abc"; s.push_back('d'); // s 变为 "abcd"
- 提示:等效于
s += c
,但push_back()
更明确表示添加单个字符。
append(const string& str)
- 定义:在字符串末尾追加另一个字符串。
- 用法:
string s = "hello"; s.append(" world"); // s 变为 "hello world"
- 提示:支持追加子串(如
append(str, pos, len)
)或字符数组。
erase(pos, len)
- 定义:从位置
pos
开始删除len
个字符(若省略len
,则删除到末尾)。 - 用法:
string s = "hello"; s.erase(1, 2); // s 变为 "hlo"
- 提示:删除后,后续字符会前移填补空缺,可能影响迭代器。
3. 字符串查找
find(const string& str, pos)
- 定义:从位置
pos
开始查找子串str
,返回首次出现的位置;若未找到,返回string::npos
。 - 用法:
string s = "hello"; size_t pos = s.find("ll"); // pos = 2
- 提示:查找失败时需检查
pos == string::npos
。
rfind(const string& str)
- 定义:从后往前查找子串,返回最后一次出现的位置。
- 用法:
string s = "abab"; size_t pos = s.rfind("ab"); // pos = 2
4. 字符串子串
substr(pos, len)
- 定义:返回从位置
pos
开始的len
个字符的子串(若省略len
,则截取到末尾)。 - 用法:
string s = "hello"; string sub = s.substr(1, 3); // sub 为 "ell"
- 提示:
substr(pos)
可用于截取后缀子串。
5. 字符串替换
replace(pos, len, const string& str)
- 定义:将从位置
pos
开始的len
个字符替换为str
。 - 用法:
string s = "hello"; s.replace(1, 3, "XYZ"); // s 变为 "hXYZo"
- 提示:替换前后的字符串长度可能不同,需注意后续字符位置变化。
6. 字符串比较
compare(const string& str)
- 定义:比较两个字符串的字典序。返回值:
0
:相等- 负值:当前字符串小于
str
- 正值:当前字符串大于
str
- 用法:
string s1 = "abc"; string s2 = "abd"; cout << s1.compare(s2); // 输出负值(如 -1)
- 提示:更常用
==
、<
、>
等运算符进行比较。
7. 字符串与数值转换
stoi(const string& str)
- 定义:将字符串转换为整数(类似的有
stol
、stod
等)。 - 用法:
string s = "123"; int num = stoi(s); // num = 123
- 提示:若字符串格式非法,会抛出
invalid_argument
或out_of_range
异常。
to_string(int value)
- 定义:将数值转换为字符串(支持各种数值类型)。
- 用法:
int num = 123; string s = to_string(num); // s = "123"
注意事项
- 迭代器失效:在修改字符串(如
erase
、insert
)后,原有的迭代器、引用和指针可能失效。 - 性能考虑:频繁的插入或删除操作可能导致内存重新分配,效率较低。
- 空字符串检查:使用
empty()
而非size() == 0
检查字符串是否为空。 - 边界检查:访问或操作字符串时,确保索引不越界(可用
at(pos)
替代[]
,越界时抛出异常)。
示例
#include <iostream>
#include <string>int main() {std::string s = "hello";// 修改s.push_back('!'); // "hello!"s.append(" world"); // "hello! world"// 查找size_t pos = s.find("world"); // 7// 替换if (pos != std::string::npos) {s.replace(pos, 5, "universe"); // "hello! universe"}// 子串std::string sub = s.substr(6, 3); // "! u"// 转换int num = 42;std::string numStr = std::to_string(num); // "42"std::cout << s << "\n"; // 输出:hello! universereturn 0;
}