字符串与文本处理
文本处理是几乎所有程序的核心需求。现代 C++ 提供了一整套高效、类型安全的字符串工具——从基础的 std::string,到零拷贝的 std::string_view,再到优雅的 std::format 格式化系统。本章将带你逐一掌握这些工具。
1. std::string 基础
std::string 是 C++ 标准库中最常用的字符串类型。它自动管理内存,支持动态增长,是处理文本的首选。
创建与拼接
#include <string>
// 创建字符串
std::string name = "Alice";
std::string greeting{"Hello"}; // 统一初始化
std::string repeated(5, '*'); // "*****"
// 拼接
std::string message = greeting + ", " + name + "!";
// message == "Hello, Alice!"
// += 追加
message += " Welcome to Modern C++.";
// append 方法
std::string path = "/usr";
path.append("/local");
path.append("/bin");
// path == "/usr/local/bin"
常用操作
std::string text = "Hello, Modern C++!";
// 长度与判空
std::size_t len = text.size(); // 18
bool empty = text.empty(); // false
// 子串
std::string sub = text.substr(7, 6); // "Modern"
// 查找
std::size_t pos = text.find("Modern"); // 7
std::size_t not_found = text.find("Java"); // std::string::npos
// 用 find 做条件判断
if (text.find("C++") != std::string::npos) {
// 找到了
}
// 替换
text.replace(7, 6, "Beautiful");
// text == "Hello, Beautiful C++!"
// 含有 (C++23 提供 contains,这里用 find 替代)
bool has_cpp = text.contains("C++"); // C++23: true
比较操作
std::string a = "apple";
std::string b = "banana";
// 直接使用比较运算符(按字典序)
bool eq = (a == b); // false
bool lt = (a < b); // true ('a' < 'b')
bool gt = (a > b); // false
// 也可以与字符串字面量比较
if (a == "apple") {
// 无需担心,不会比较指针地址
}
用 range-for 遍历字符
std::string word = "C++26";
// 遍历每个字符
for (char c : word) {
std::println("char: {}", c);
}
// 需要修改时用引用
std::string lower = "HELLO";
for (char& c : lower) {
c = std::tolower(static_cast<unsigned char>(c));
}
// lower == "hello"
提示:
std::string 内部使用「小字符串优化」(SSO)。短字符串(通常 ≤ 15 或 22 字节)直接存储在栈上对象内部,不需要堆分配。这意味着创建短字符串的开销极低。
2. std::string_view (C++17)
std::string_view 是一个非拥有、只读的字符串视图。它不管理内存,仅持有一个指针和长度,因此拷贝和传参的开销极低。
为什么需要 string_view?
// 问题:这个函数只是"看一下"字符串,却可能产生不必要的拷贝
void old_style(const std::string& s); // 传 "hello" 字面量时会构造临时 string
// 解决:string_view 零拷贝接收任何字符串
#include <string_view>
void modern_style(std::string_view s); // 传什么都不拷贝
作为函数参数
#include <string>
#include <string_view>
#include <print>
void print_info(std::string_view text) {
std::println("Length: {}, Content: \"{}\"", text.size(), text);
}
int main() {
print_info("literal"); // 字面量,零拷贝
print_info(std::string{"owned"}); // string,零拷贝视图
std::string data = "Hello, World!";
print_info(data); // 已有 string,零拷贝
// string_view 支持 substr, find, starts_with 等操作
std::string_view sv = data;
std::println("Starts with Hello? {}", sv.starts_with("Hello"));
std::println("Ends with '!'? {}", sv.ends_with("!"));
}
string_view 支持的操作
std::string_view sv = "Hello, Modern C++!";
sv.size(); // 18
sv.empty(); // false
sv.substr(7, 6); // "Modern" (返回 string_view)
sv.find("C++"); // 15
sv.starts_with("Hello"); // true (C++20)
sv.ends_with("!"); // true (C++20)
sv.contains("Modern"); // true (C++23)
// 缩小视图范围(不修改底层数据)
sv.remove_prefix(7); // sv 现在是 "Modern C++!"
sv.remove_suffix(1); // sv 现在是 "Modern C++"
生命周期陷阱!
string_view 不拥有数据。如果底层字符串被销毁或修改,string_view 就会悬空(dangling)。
// 危险示例!
std::string_view get_name() {
std::string local = "Alice";
return local; // 错误!local 在函数返回后销毁,view 悬空
}
// 安全做法:确保 view 不会超出数据的生命周期
std::string_view safe_view(const std::string& s) {
return s; // OK:调用者保证 s 的生命周期
}
// 规则:string_view 用于"借用",不用于"拥有"
// 需要存储字符串时,使用 std::string
使用准则:当函数只需要"读取"字符串内容时,参数用
std::string_view;当函数需要"拥有"或"修改"字符串时,参数用 std::string 或 std::string&。
3. std::format (C++20)
C++20 引入的 std::format 是一个类型安全、可扩展的格式化库,灵感来自 Python 的格式化语法。它取代了 printf(不安全)和 << 流操作(冗长),成为现代 C++ 格式化的首选。
基本语法
#include <format>
#include <string>
std::string name = "Alice";
int age = 30;
// {} 是占位符,按顺序替换
auto msg = std::format("Name: {}, Age: {}", name, age);
// "Name: Alice, Age: 30"
// 位置参数:{0}, {1} 指定使用第几个参数
auto msg2 = std::format("{0} is {1} years old. Hi, {0}!", name, age);
// "Alice is 30 years old. Hi, Alice!"
格式说明符
// 语法: {[参数索引]:[填充][对齐][宽度][.精度][类型]}
// 宽度与对齐
std::format("{:10}", "hi"); // "hi " (默认左对齐字符串)
std::format("{:>10}", "hi"); // " hi" (右对齐)
std::format("{:^10}", "hi"); // " hi " (居中)
std::format("{:*^10}", "hi"); // "****hi****" (用 * 填充,居中)
// 数字格式化
std::format("{:d}", 42); // "42" (十进制,默认)
std::format("{:x}", 255); // "ff" (十六进制)
std::format("{:#x}", 255); // "0xff" (带前缀的十六进制)
std::format("{:#b}", 10); // "0b1010"(带前缀的二进制)
std::format("{:08d}", 42); // "00000042" (零填充,宽度8)
// 浮点数
std::format("{:.2f}", 3.14159); // "3.14" (2位小数)
std::format("{:.4f}", 3.14159); // "3.1416" (4位小数)
std::format("{:e}", 12345.6); // "1.23456e+04" (科学计数)
std::format("{:10.3f}", 3.14); // " 3.140" (宽度10,3位小数)
// 布尔值
std::format("{}", true); // "true"
与 printf 和 cout 的对比
std::string name = "World";
double pi = 3.14159;
// C 风格 printf —— 不安全,类型错误不报错
printf("Hello %s, pi = %.2f\n", name.c_str(), pi);
// iostream 风格 —— 类型安全但冗长
std::cout << "Hello " << name << ", pi = "
<< std::fixed << std::setprecision(2) << pi << "\n";
// std::format —— 类型安全 + 简洁
auto s = std::format("Hello {}, pi = {:.2f}", name, pi);
优势总结:
std::format 编译时检查格式字符串(C++26 后更严格),类型安全,不会因类型不匹配导致未定义行为;语法简洁直观,可读性远超 iostream。
4. std::println 与格式化输出
C++23 引入了 std::print 和 std::println,将 std::format 与输出合二为一,彻底告别 std::cout 的繁琐。
#include <print>
// std::println = std::print + 换行符
std::println("Hello, {}!", "World"); // 输出: Hello, World!\n
std::print("No newline here"); // 不自动换行
// 数字格式化直接输出
int score = 95;
std::println("Score: {:>5}", score); // "Score: 95"
// 表格对齐示例
std::println("{:8} | {:>6}", "Name", "Score", "Grade");
std::println("{:-8}-+-{:->6}", "", "", "");
std::println("{:8} | {:>6}", "Alice", 95, "A+");
std::println("{:8} | {:>6}", "Bob", 82, "B");
std::println("{:8} | {:>6}", "Charlie", 71, "C");
// 输出:
// Name | Score | Grade
// -----------+----------+-------
// Alice | 95 | A+
// Bob | 82 | B
// Charlie | 71 | C
宽度、对齐与填充字符
// 填充字符 + 对齐
std::println("{:*>20}", "right"); // "***************right"
std::println("{:*{}}{: >{}}] {}%",
"", filled, "", empty, percent);
}
// 输出到 stderr
std::println(stderr, "Error: file {} not found", filename);
提示:
std::println 输出的换行符始终是 \n,即使在 Windows 上也不会自动转换为 \r\n(除非文件以文本模式打开)。这与 std::endl 不同,println 不会刷新缓冲区。
5. 字符串转换
在实际开发中,经常需要在字符串与数值之间相互转换。现代 C++ 提供了多种方式,从简单到高性能都有覆盖。
数字转字符串:std::to_string
#include <string>
auto s1 = std::to_string(42); // "42"
auto s2 = std::to_string(3.14); // "3.140000" (注意精度)
auto s3 = std::to_string(-100); // "-100"
// 更精确的控制?用 std::format
auto s4 = std::format("{:.2f}", 3.14); // "3.14"
字符串转数字:stoi / stod 系列
#include <string>
int n = std::stoi("42"); // 42
long l = std::stol("1000000"); // 1000000
double d = std::stod("3.14"); // 3.14
float f = std::stof("2.718"); // 2.718f
// 可以指定起始位置和进制
int hex_val = std::stoi("ff", nullptr, 16); // 255
int bin_val = std::stoi("1010", nullptr, 2); // 10
// 异常处理
try {
int bad = std::stoi("not_a_number");
} catch (const std::invalid_argument& e) {
std::println("Invalid: {}", e.what());
} catch (const std::out_of_range& e) {
std::println("Out of range: {}", e.what());
}
高性能转换:from_chars / to_chars (C++17)
#include <charconv>
#include <system_error>
// to_chars:数字 → 字符数组(无内存分配)
char buffer[20];
auto [ptr, ec] = std::to_chars(buffer, buffer + 20, 3.14159);
if (ec == std::errc{}) {
std::string_view result(buffer, ptr - buffer);
std::println("Converted: {}", result); // "3.14159"
}
// from_chars:字符数组 → 数字(无内存分配)
std::string_view input = "12345";
int value = 0;
auto [p, err] = std::from_chars(input.data(),
input.data() + input.size(),
value);
if (err == std::errc{}) {
std::println("Parsed: {}", value); // 12345
}
性能对比:
std::from_chars / std::to_chars 不分配内存、不抛异常、不考虑 locale,是解析大量数据(如读取 CSV 文件)时的最佳选择。在基准测试中,它们通常比 stoi/stod 快 5-10 倍。
6. 实用技巧
用户自定义字面量后缀
#include <string>
#include <string_view>
using namespace std::literals; // 启用字面量后缀
// "..."s 创建 std::string
auto str = "hello"s; // 类型:std::string
auto str2 = "world"s;
// "..."sv 创建 std::string_view
auto sv = "hello"sv; // 类型:std::string_view
// 为什么有用?auto 推导字面量时默认是 const char*
auto raw = "hello"; // const char* (不是 string!)
auto owned = "hello"s; // std::string (明确拥有)
auto view = "hello"sv; // std::string_view (明确借用)
// 在拼接中也很有用
auto combined = "Hello"s + ", " + "World"s; // OK: string + const char*
// auto bad = "Hello" + "World"; // 错误!const char* 不能相加
原始字符串字面量
// 普通字符串中反斜杠需要转义
std::string path = "C:\\Users\\Alice\\Documents";
std::string regex = "\\d+\\.\\d+";
// R"(...)" 原始字符串——所见即所得,无需转义
std::string path2 = R"(C:\Users\Alice\Documents)";
std::string regex2 = R"(\d+\.\d+)";
// 包含引号和括号时,可以自定义分隔符
std::string json = R"json(
{
"name": "Alice",
"age": 30,
"path": "C:\temp"
}
)json";
// 多行文本非常方便
std::string sql = R"(
SELECT name, age
FROM users
WHERE age > 18
ORDER BY name
)";
实用代码片段
// 判断前缀/后缀 (C++20)
std::string filename = "report.pdf";
if (filename.ends_with(".pdf")) {
std::println("It's a PDF file");
}
if (filename.starts_with("report")) {
std::println("It's a report");
}
// 分割字符串(使用 string_view 避免拷贝)
#include <ranges>
#include <string_view>
std::string csv = "apple,banana,cherry";
for (auto word : csv | std::views::split(',')) {
std::string_view token(word.begin(), word.end());
std::println(" {}", token);
}
// 输出:
// apple
// banana
// cherry
注意:
std::views::split 返回的子范围在 C++20 中使用稍有不便(需要手动构造 string_view)。C++23 的改进使其更易用。如果项目需要频繁分割字符串,也可以考虑简单的辅助函数。
本章小结
std::string是拥有型字符串,支持拼接、查找、替换等丰富操作,短字符串有 SSO 优化std::string_view是非拥有的只读视图,函数参数首选,零拷贝但需注意生命周期std::format提供类型安全、简洁直观的格式化,支持宽度/对齐/精度/进制控制std::println将格式化与输出合一,告别std::cout <<的连锁写法std::to_string/std::stoi用于简单转换;from_chars/to_chars用于高性能场景- 善用字面量后缀
"..."s和"..."sv,以及原始字符串R"(...)"简化代码