c++中如何判断字符串是否包含子串_c++子串查找方法

使用find方法可判断子串是否存在,若返回值不为std::string::npos则包含;2. 对C风格字符串可用strstr函数,需包含头文件;3. std::search算法提供更灵活的查找方式,支持自定义匹配规则;4. 可封装containsSubstring函数实现简洁调用。最常用的是find方法。

c++中如何判断字符串是否包含子串_c++子串查找方法

在C++中判断一个字符串是否包含某个子串,有多种方法可以实现。最常用的是利用标准库 std::string 提供的 find 函数。下面介绍几种实用且高效的子串查找方式。

使用 find 方法判断子串是否存在

std::string::find 是最直接的方式,用于查找子串在原字符串中的位置。如果找不到,返回 std::string::npos

示例代码:

#include 
#include

int main() {
std::string str = "Hello, this is a test string.";
std::string substr = "test";

if (str.find(substr) != std::string::npos) {
std::cout << "包含子串: " << substr << std::endl;
} else {
std::cout << "不包含子串" << std::endl;
}
return 0;
}

只要结果不是 std::string::npos,就说明子串存在。

立即学习“C++免费学习笔记(深入)”;

使用 strstr(C风格字符串)

对于C风格字符串(即字符数组或 const char*),可以用 strstr 函数,它来自

示例代码:

#include 
#include

int main() {
const char* str = "Hello world from C++";
const char* substr = "world";

if (strstr(str, substr) != nullptr) {
std::cout << "找到子串" << std::endl;
} else {
std::cout << "未找到子串" << std::endl;
}
return 0;
}

注意:这种方法适用于C字符串,对 std::string 需要调用 .c_str() 转换。

使用 std::search(STL算法)

C++标准库中的 std::search 算法也可以用来查找子串,适用于更灵活的匹配场景。

示例代码:

#include 
#include
#include

int main() {
std::string str = "Find me the word example";
std::string pattern = "example";

auto it = std::search(str.begin(), str.end(),
pattern.begin(), pattern.end());

if (it != str.end()) {
std::cout << "子串在位置 " << (it - str.begin()) << " 找到" << std::endl;
} else {
std::cout << "未找到子串" << std::endl;
}
return 0;
}

这种方式更通用,还可以配合自定义比较函数使用。

封装成可复用的函数

为了方便多次使用,可以封装一个布尔函数:

bool containsSubstring(const std::string& str, const std::string& substr) {
return str.find(substr) != std::string::npos;
}

调用起来简洁明了:

if (containsSubstring(text, "key")) { ... }

基本上就这些常用方法。find 最简单直接,适合大多数情况;strstr 适合处理C字符串;std::search 更灵活但略显复杂。选择哪种取决于你的数据类型和需求。

以上就是c++++中如何判断字符串是否包含子串_c++子串查找方法的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1479307.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月19日 03:40:57
下一篇 2025年12月19日 03:41:03

相关推荐

发表回复

登录后才能评论
关注微信