C++: 字符串操作进阶
最后更新:2026-08-26
第19课我们学了 string 的基础操作。
但真实场景中,你可能需要删除字符、插入字符、比较字符串、把数字转成字符串……
这一课,我们来学 string 的进阶操作。
1. 修改字符串
(1) 1.1 删除字符(erase)
语法:
▶ 示例 2:代码示例(难度⭐)
string.erase(startPos, deleteCount);
输出:
(程序输出)
示例:
#include <iostream>
#include <string>
int main() {
std::string text = "Hello, World!";
// 删除从第 5 个字符开始的 7 个字符(", World")
text.erase(5, 7);
std::cout << text << std::endl; // Hello!
return 0;
}
💡 提示: 如果只传一个参数,erase(pos) 会删除从 pos 到末尾的所有字符。
(2) 1.2 插入字符(insert)
语法:
string.insert(插入位置, 要插入的字符串);
示例:
#include <iostream>
#include <string>
int main() {
std::string text = "Hello!";
// 在第 5 个字符前插入 " World"
text.insert(5, " World");
std::cout << text << std::endl; // Hello World!
return 0;
}
(3) 1.3 清空字符串(clear)
#include <iostream>
#include <string>
int main() {
std::string text = "Hello";
text.clear(); // 清空字符串
std::cout << "长度:" << text.length() << std::endl; // 0
std::cout << "是否为空:" << text.empty() << std::endl; // 1(true)
return 0;
}
💡 提示: empty() 函数用来判断字符串是否为空(为空返回 true,即 1)。
2. 比较字符串(compare)
虽然可以用 ==、!=、<、> 比较 string,但 compare() 函数能提供更详细的信息。
(1) 2.1 基本用法
#include <iostream>
#include <string>
int main() {
std::string s1 = "apple";
std::string s2 = "banana";
int result = s1.compare(s2);
if (result == 0) {
std::cout << "s1 和 s2 相等" << std::endl;
} else if (result < 0) {
std::cout << "s1 小于 s2" << std::endl; // 这行会执行
} else {
std::cout << "s1 大于 s2" << std::endl;
}
return 0;
}
返回值:
0:两个字符串相等< 0:调用者小于参数> 0:调用者大于参数
💡 提示: 实际上,直接用 ==、!=、<、> 比较 string 更直观,推荐用这些运算符。
3. 字符串与数字的互相转换
(1) 3.1 数字转字符串(to_string)
#include <iostream>
#include <string>
int main() {
int age = 25;
double price = 19.99;
std::string ageStr = std::to_string(age);
std::string priceStr = std::to_string(price);
std::cout << "年龄:" << ageStr << std::endl;
std::cout << "价格:" << priceStr << std::endl;
return 0;
}
💡 提示: to_string() 转换浮点数时,会保留 6 位小数。如果想控制格式,用 std::ostringstream 或 std::format(C++20)。
(2) 3.2 字符串转数字(stoi、stod)
| 函数 | 作用 | 示例 |
|---|---|---|
std::stoi(str) |
字符串 → int | int x = std::stoi("123"); |
std::stol(str) |
字符串 → long | long x = std::stol("123"); |
std::stoll(str) |
字符串 → long long | long long x = std::stoll("123"); |
std::stof(str) |
字符串 → float | float x = std::stof("3.14"); |
std::stod(str) |
字符串 → double | double x = std::stod("3.14"); |
示例:
#include <iostream>
#include <string>
int main() {
std::string numStr = "123";
std::string priceStr = "19.99";
int num = std::stoi(numStr);
double price = std::stod(priceStr);
std::cout << "num = " << num << std::endl;
std::cout << "price = " << price << std::endl;
return 0;
}
⚠️ 注意: 如果字符串不是合法的数字格式,stoi / stod 会抛异常。后面会学如何用 try-catch 处理。
4. 遍历字符串
(1) 4.1 用下标
#include <iostream>
#include <string>
int main() {
std::string text = "Hello";
for (size_t i = 0; i < text.length(); i++) {
std::cout << text[i] << " ";
}
std::cout << std::endl;
return 0;
}
(2) 4.2 用范围 for(C++11,推荐)
#include <iostream>
#include <string>
int main() {
std::string text = "Hello";
for (char c : text) {
std::cout << c << " ";
}
std::cout << std::endl;
return 0;
}
💡 提示: 范围 for 更简洁,且不容易写错循环条件。
5. 实战:简单的文本编辑器
▶ 示例 1:实现"查找并替换"功能(难度⭐⭐)
#include <iostream>
#include <string>
int main() {
std::string text = "I like C. C is powerful.";
std::string oldStr = "C";
std::string newStr = "C++";
size_t pos = 0;
while ((pos = text.find(oldStr, pos)) != std::string::npos) {
text.replace(pos, oldStr.length(), newStr);
pos += newStr.length(); // 避免无限循环
}
std::cout << "替换后:" << text << std::endl;
return 0;
}
输出:
替换后:
💡 重点: 替换后,要跳过新插入的字符串,否则会无限循环(如果新字符串包含旧字符串)。
▶ 示例 3:用 substr 截取子串(难度⭐)
#include <iostream>
#include <string>
int main() {
std::string text = "Hello, C++ World!";
// 截取 "Hello"
std::string part1 = text.substr(0, 5);
std::cout << "part1: " << part1 << std::endl;
// 截取 "C++"
std::string part2 = text.substr(7, 3);
std::cout << "part2: " << part2 << std::endl;
// 从位置7截取到末尾
std::string part3 = text.substr(7);
std::cout << "part3: " << part3 << std::endl;
return 0;
}
输出:
part1:
part2:
part3:
❓ 常见问题
string::length() 返回的是 size_t(无符号整数)。如果用 int,在比较时可能会出现警告(有符号 vs 无符号)。std::invalid_argument 异常。📖 小节
erase()删除字符,insert()插入字符,clear()清空字符串compare()比较字符串(但推荐直接用==、!=等运算符)to_string()把数字转成字符串stoi()/stod()把字符串转成数字- 遍历字符串推荐用范围 for(C++11)
📝 作业
- 基础题 (Difficulty ⭐): 写一个程序,让用户输入一个字符串,然后删除里面所有的空格。
输入:Hello World, this is C++!
输出:HelloWorld,thisisC++!
-
进阶题 (Difficulty ⭐⭐): 写一个程序,让用户输入一个字符串,判断它是否是"回文"(正着读和反着读一样,如 "level"、"radar")。
-
提示:可以用两个指针(或索引),一个从前往后,一个从后往前,逐个比较。
-
挑战题 (Difficulty ⭐⭐⭐): 写一个程序,实现"简单的加密/解密":
-
加密规则:把每个字符的 ASCII 码加 3(如
'A'→'D') -
解密规则:把每个字符的 ASCII 码减 3
-
让用户输入字符串,先加密再解密,输出结果
- 查找:find/rfind/find_first_of 定位子串
- 截取:substr(pos, count) 提取子串
- 替换:replace(pos, count, str) 替换部分内容
- 插入/删除:insert/erase 动态修改字符串
- 类型转换:stoi/stod/to_string 在字符串和数字间转换
6. 🚀 下一步
学会了字符串的进阶操作,接下来我们进入 Phase 4(指针与引用),这是 C++ 最"劝退"但也最重要的部分——理解内存,才能写出高效的代码!