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

在C++中,检查一个字符串是否包含某个子串有多种方法,最常用的是利用标准库 std::string 提供的 find 函数。如果想判断子串是否存在,只需检查 find 的返回值是否为 std::string::npos。
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 区分大小写,且支持从指定位置开始查找,适用于多次查找场景。
立即学习“C++免费学习笔记(深入)”;
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 的正确判断。
以上就是c++++如何检查string是否包含子串_c++字符串查找子串方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号