使用find函数判断子串是否存在,返回值不等于std::string::npos表示找到,否则未找到,注意区分大小写并正确比较npos,日常推荐使用find方法。

在C++中,检查一个字符串是否包含某个子串有多种方法,最常用的是利用标准库 std::string 提供的 find 函数。如果想判断子串是否存在,只需检查 find 的返回值是否为 std::string::npos。
使用 find 方法查找子串
std::string::find 用于搜索子串在原字符串中的位置,若找到则返回起始索引,未找到则返回 std::string::npos。
- 返回值不等于
std::string::npos:表示找到了子串 - 返回值等于
std::string::npos:表示未找到
示例代码:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, this is a test string";
std::string substr = "test";
if (str.find(substr) != std::string::npos) {
std::cout << "子串存在" << std::endl;
} else {
std::cout << "子串不存在" << std::endl;
}
return 0;
}
使用 find 的注意事项
find 区分大小写,且支持从指定位置开始查找,适用于多次查找场景。
立即学习“C++免费学习笔记(深入)”;
- 查找从第5个字符开始:
str.find("is", 5) - 查找失败时始终返回
std::string::npos,建议用常量比较 - 性能良好,适合大多数字符串查找需求
其他查找方式(可选)
除了 find,还可以使用标准算法库中的 std::search 或正则表达式 std::regex_search,但通常更复杂,适用于特殊场景。
例如使用正则判断是否包含数字:
#include <iostream>
#include <string>
#include <regex>
int main() {
std::string str = "There are 123 apples";
std::regex pattern("\d+");
if (std::regex_search(str, pattern)) {
std::cout << "字符串包含数字" << std::endl;
}
return 0;
}
基本上就这些。日常使用 find 就足够了,简单高效,是C++中最推荐的子串查找方式。不复杂但容易忽略的是对 npos 的正确判断。











