在C++中检查字符串是否包含另一个字符串
- 论坛
- 在C++中检查字符串是否包含另一个字符串
42 浏览
在C++中检查字符串是否包含另一个字符串
我有一个类型为std::string
的变量。我想检查它是否包含某个std::string
。我该如何做呢?
有没有一种函数可以返回如果找到了字符串就是true,没找到就是false?
admin 更改状态以发布 2023年5月21日
匿名的
0 Comments
你可以尝试使用find
函数:
string str ("There are two needles in this haystack."); string str2 ("needle"); if (str.find(str2) != string::npos) { //.. found. }
匿名的
0 Comments
使用std::string::find
函数,如下所示:
if (s1.find(s2) != std::string::npos) { std::cout << "found!" << ' '; }
注意:如果s2
是s1
的子字符串,则会打印出“found!”。其中s1
和s2
都是类型为std::string
的变量。