C++中判断字符串包含子串常用find函数,如str.find(substr) != std::string::npos表示找到;可转换为小写实现忽略大小写查找;也可用std::search配合自定义比较函数;复杂场景可用正则表达式regex_search。

在C++中判断一个字符串是否包含某个子串,有多种方法可以实现。最常用的是利用标准库 std::string 提供的成员函数 find,也可以结合其他方式如 std::search 或第三方库(如正则表达式)来完成。下面详细介绍几种实用且高效的查找方法。
使用 find 函数查找子串
std::string::find 是最直接、最常用的方法。它会在主串中搜索指定的子串,如果找到,返回子串首次出现的位置;未找到则返回 std::string::npos。
示例代码:
#include#include int main() { std::string str = "Hello, this is a sample string."; std::string substr = "sample";
if (str.find(substr) != std::string::npos) { std::cout << "找到了子串!" << std::endl; } else { std::cout << "未找到子串。" << std::endl; } return 0;}
说明:只要
find返回值不是std::string::npos,就表示包含该子串。立即学习“C++免费学习笔记(深入)”;
不区分大小写的子串查找
C++ 标准库没有提供直接的忽略大小写查找方法,需要手动转换或逐字符比较。
一种简单实现是先将主串和子串都转为小写,再用
find比较:#include#include #include #include std::string toLower(const std::string& s) { std::string result = s; std::transform(result.begin(), result.end(), result.begin(), [](unsigned char c){ return std::tolower(c); }); return result; }
int main() { std::string str = "Hello, THIS is awesome!"; std::string substr = "this";
if (toLower(str).find(toLower(substr)) != std::string::npos) { std::cout << "找到了(忽略大小写)!" << std::endl; } return 0;}
这种方法适用于对性能要求不高的场景。
使用标准算法 search 进行自定义匹配
std::search 是
中的通用搜索函数,可用于在字符序列中查找子序列,支持自定义比较函数。例如,实现忽略大小写的查找:
#include#include #include #include bool caseInsensitiveCharCompare(char a, char b) { return std::tolower(a) == std::tolower(b); }
int main() { std::string str = "C++ is powerful"; std::string substr = "POWERFUL";
auto it = std::search(str.begin(), str.end(), substr.begin(), substr.end(), caseInsensitiveCharCompare); if (it != str.end()) { std::cout << "找到了,位置:" << (it - str.begin()) << std::endl; } else { std::cout << "未找到。" << std::endl; } return 0;}
这种方式更灵活,适合复杂匹配逻辑。
使用正则表达式进行模式匹配
对于更复杂的子串匹配需求(比如模糊匹配、通配符等),可以使用
库。 #include#include #include int main() { std::string text = "Contact us at support@example.com today."; std::regex pattern(R"(\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b)");
if (std::regex_search(text, pattern)) { std::cout << "发现了邮箱地址!" << std::endl; } return 0;}
虽然用于简单子串查找有些“杀鸡用牛刀”,但在处理复杂文本时非常强大。
基本上就这些常见方法。日常开发中,find 足以应对大多数子串查找需求,简洁高效。遇到特殊要求时,再考虑转换大小写、使用 std::search 或正则表达式。掌握这些技巧,字符串处理会更加得心应手。











