C++中查找子串常用std::string的find()函数,它返回子串首次出现的位置,未找到则返回std::string::npos;还可使用rfind()从右查找、实现忽略大小写查找或借助进行复杂匹配。

在C++中查找字符串中的子串,常用的方法依赖于标准库std::string提供的成员函数。这些方法简单高效,适合大多数场景。
使用 find() 函数查找子串
find() 是最常用的子串查找方式,它返回子串第一次出现的位置索引,如果未找到则返回 std::string::npos。
- 返回值为
size_t类型,表示匹配位置的下标(从0开始) - 若未找到,返回
std::string::npos(通常为 -1 转换为无符号最大值) - 支持从指定位置开始查找
示例代码:
#include#include int main() { std::string str = "Hello, welcome to C++ programming!"; std::string substr = "welcome"; size_t pos = str.find(substr); if (pos != std::string::npos) { std::cout << "子串在位置 " << pos << " 找到。\n"; } else { std::cout << "未找到子串。\n"; } return 0; }
其他查找函数变体
C++ 提供了多个 find 相关函数,满足不同查找需求:
立即学习“C++免费学习笔记(深入)”;
- rfind():从右往左查找,返回最后一次出现的位置
- find_first_of():查找任意一个匹配字符的首次出现(不是完整子串)
- find_last_of():查找任意一个匹配字符的最后一次出现
- find_first_not_of() 和 find_last_not_of():查找不匹配的字符
若只想找完整子串,应使用 find() 或 rfind()。
忽略大小写的查找实现
标准库没有直接提供忽略大小写的查找,需手动实现。常见做法是将原字符串和子串都转为小写后再查找。
示例:
#include#include #include #include std::string toLower(const std::string& s) { std::string lower = s; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); return lower; } size_t findIgnoreCase(const std::string& str, const std::string& substr) { return toLower(str).find(toLower(substr)); } int main() { std::string text = "C++ is awesome!"; std::string key = "c++"; if (findIgnoreCase(text, key) != std::string::npos) { std::cout << "找到了(忽略大小写)\n"; } return 0; }
基本上就这些。对于常规子串查找,find() 完全够用。需要更复杂模式匹配时,可考虑使用 库。不过对于简单查找,std::string::find 更轻量、易读、高效。











