字符串成员函数 contains / starts_with / ends_with
概述
C++20 为 std::string 和 std::string_view 添加了 starts_with() 和 ends_with() 成员函数,C++23 进一步添加了 contains() 成员函数。这三个函数让字符串的前缀、后缀和包含检测变得非常直观,不再需要手动用 find()、substr() 或 compare() 来实现。
C++20/23 之前 vs 之后
| 操作 | C++17 及之前 | C++20/23 |
|---|---|---|
| 检查前缀 | s.find("prefix") == 0 或 s.substr(0, n) == "prefix" | s.starts_with("prefix") |
| 检查后缀 | s.size() >= n && s.compare(s.size()-n, n, "suffix") == 0 | s.ends_with("suffix") |
| 检查包含 | s.find("sub") != std::string::npos | s.contains("sub")(C++23) |
基本示例
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
// ============================
// 示例1:starts_with(C++20)
// ============================
void starts_with_demo() {
std::string url = "https://www.example.com/page";
// 检查字符串前缀
std::cout << std::boolalpha;
std::cout << "以 https 开头: " << url.starts_with("https") << std::endl; // true
std::cout << "以 http 开头: " << url.starts_with("http") << std::endl; // true
std::cout << "以 ftp 开头: " << url.starts_with("ftp") << std::endl; // false
// 检查单个字符
std::cout << "以 'h' 开头: " << url.starts_with('h') << std::endl; // true
// 用 string_view 参数
std::string_view prefix = "https://";
std::cout << "以 https:// 开头: " << url.starts_with(prefix) << std::endl; // true
// 空字符串——任何字符串都以空串开头
std::cout << "以空串开头: " << url.starts_with("") << std::endl; // true
}
// ============================
// 示例2:ends_with(C++20)
// ============================
void ends_with_demo() {
std::string filename = "document.pdf";
// 检查文件扩展名
std::cout << std::boolalpha;
std::cout << "以 .pdf 结尾: " << filename.ends_with(".pdf") << std::endl; // true
std::cout << "以 .txt 结尾: " << filename.ends_with(".txt") << std::endl; // false
std::cout << "以 .PDF 结尾: " << filename.ends_with(".PDF") << std::endl; // false(区分大小写)
// 检查单个字符
std::cout << "以 'f' 结尾: " << filename.ends_with('f') << std::endl; // true
// 实际应用:过滤特定后缀的文件
std::vector<std::string> files = {
"main.cpp", "header.h", "data.txt", "config.json", "test.cpp"
};
std::cout << "C++ 源文件: ";
for (const auto& f : files) {
if (f.ends_with(".cpp")) {
std::cout << f << " ";
}
}
std::cout << std::endl; // main.cpp test.cpp
}
// ============================
// 示例3:contains(C++23)
// ============================
void contains_demo() {
std::string text = "Hello, World! Welcome to C++23.";
// 检查是否包含子串
std::cout << std::boolalpha;
std::cout << "包含 World: " << text.contains("World") << std::endl; // true
std::cout << "包含 world: " << text.contains("world") << std::endl; // false(区分大小写)
std::cout << "包含 C++: " << text.contains("C++") << std::endl; // true
// 检查单个字符
std::cout << "包含 '!': " << text.contains('!') << std::endl; // true
std::cout << "包含 '?': " << text.contains('?') << std::endl; // false
// 用 string_view
std::string_view sub = "Welcome";
std::cout << "包含 Welcome: " << text.contains(sub) << std::endl; // true
}
// ============================
// 示例4:string_view 也支持
// ============================
void string_view_demo() {
std::string_view sv = "Hello, World!";
// string_view 同样支持这三个函数
std::cout << std::boolalpha;
std::cout << "starts_with: " << sv.starts_with("Hello") << std::endl; // true
std::cout << "ends_with: " << sv.ends_with("World!") << std::endl; // true
std::cout << "contains: " << sv.contains("lo, W") << std::endl; // true(C++23)
}
// ============================
// 示例5:实际应用——URL 解析
// ============================
void url_demo() {
std::vector<std::string> urls = {
"https://example.com/api/users",
"http://example.com/page",
"ftp://files.example.com/data",
"https://example.com/api/products",
"https://example.com/about",
};
// 筛选 HTTPS 的 API 请求
std::cout << "HTTPS API 请求:" << std::endl;
for (const auto& url : urls) {
if (url.starts_with("https://") && url.contains("/api/")) {
std::cout << " " << url << std::endl;
}
}
}
// ============================
// 示例6:实际应用——日志过滤
// ============================
void log_demo() {
std::vector<std::string> logs = {
"[ERROR] 连接超时",
"[INFO] 服务启动成功",
"[WARNING] 内存使用率 85%",
"[ERROR] 文件未找到",
"[DEBUG] 请求参数: id=42",
"[INFO] 请求处理完成",
};
// 筛选错误日志
std::cout << "错误日志:" << std::endl;
for (const auto& log : logs) {
if (log.starts_with("[ERROR]")) {
std::cout << " " << log << std::endl;
}
}
// 筛选包含"内存"的日志
std::cout << "\n包含'内存'的日志:" << std::endl;
for (const auto& log : logs) {
if (log.contains("内存")) {
std::cout << " " << log << std::endl;
}
}
}
// ============================
// 示例7:实际应用——配置文件解析
// ============================
void config_demo() {
std::vector<std::string> lines = {
"# 这是注释",
"name=Alice",
" # 另一行注释",
"age=25",
"",
"city=Beijing",
};
std::cout << "配置项:" << std::endl;
for (const auto& line : lines) {
// 跳过空行和注释
if (line.empty()) continue;
// 去掉前导空格后检查是否是注释
std::string_view sv = line;
auto pos = sv.find_first_not_of(" \t");
if (pos != std::string_view::npos) {
sv = sv.substr(pos);
}
if (sv.starts_with("#")) continue;
// 检查是否包含 '='
if (sv.contains('=')) {
std::cout << " " << sv << std::endl;
}
}
}
int main() {
std::cout << "=== starts_with ===" << std::endl;
starts_with_demo();
std::cout << "\n=== ends_with ===" << std::endl;
ends_with_demo();
std::cout << "\n=== contains ===" << std::endl;
contains_demo();
std::cout << "\n=== string_view ===" << std::endl;
string_view_demo();
std::cout << "\n=== URL 解析 ===" << std::endl;
url_demo();
std::cout << "\n=== 日志过滤 ===" << std::endl;
log_demo();
std::cout << "\n=== 配置解析 ===" << std::endl;
config_demo();
return 0;
}三个函数的签名
// std::string 和 std::string_view 都支持
// C++20
bool starts_with(std::string_view sv) const noexcept;
bool starts_with(char c) const noexcept;
bool starts_with(const char* s) const;
bool ends_with(std::string_view sv) const noexcept;
bool ends_with(char c) const noexcept;
bool ends_with(const char* s) const;
// C++23
bool contains(std::string_view sv) const noexcept;
bool contains(char c) const noexcept;
bool contains(const char* s) const;每个函数都有三个重载:接受 string_view、单个字符、或 C 字符串。
适用场景
- 检查文件扩展名(ends_with)
- 检查 URL 协议前缀(starts_with)
- 搜索子串(contains)
- 日志过滤
- 配置文件解析
- 命令行参数检测
常见问题
这些函数区分大小写吗?
是的。这三个函数都是大小写敏感的。如果需要忽略大小写的比较,需要先将字符串转为统一大小写再比较。
空字符串的行为是什么?
任何字符串都以空串开头(starts_with("") 返回 true),以空串结尾(ends_with("") 返回 true),且包含空串(contains("") 返回 true)。
contains 和 find 有什么区别?
contains 返回 bool,只告诉你是否包含。find 返回位置(size_t),还能告诉你子串在哪里。如果只需要判断是否包含,contains 更简洁直观。
这些函数的时间复杂度是多少?
starts_with 和 ends_with 是 O(m) 的(m 是前缀/后缀长度)。contains 是 O(n*m) 的(和 find 相同)。
注意事项
- starts_with 和 ends_with 是 C++20,contains 是 C++23
- 三个函数都区分大小写
- 三个函数都是 noexcept 的(string_view 和 char 重载)
- 空串参数总是返回 true
- 这些函数不修改字符串
编译器支持情况
| 编译器 | starts_with / ends_with | contains | 最低版本 |
|---|---|---|---|
| GCC | C++20 支持 | C++23 支持 | 11.0 / 13.0 |
| Clang | C++20 支持 | C++23 支持 | 12.0 / 15.0 |
| MSVC | C++20 支持 | C++23 支持 | 19.29 / 19.34 |
总结
starts_with、ends_with(C++20)和 contains(C++23)是标准库对字符串操作长期缺失的补充。这三个函数让前缀、后缀和包含检测从原来需要 find、substr、compare 的多步操作变成了一次直观的调用。它们同时在 std::string 和 std::string_view 上可用,支持字符串、单字符和 C 字符串参数。虽然功能简单,但在日常编程中使用频率非常高,显著提升了代码可读性。