C++ 判断string 中是否包含某个字符串
时间: 2023-08-11 21:07:40 浏览: 114
可以使用 `find()` 函数来判断一个 `string` 是否包含另一个字符串。
例如,假设我们要判断字符串 `s` 是否包含字符串 `t`,可以使用以下代码:
```cpp
if (s.find(t) != string::npos) {
// 字符串 s 包含字符串 t
} else {
// 字符串 s 不包含字符串 t
}
```
其中,`find()` 函数返回字符串 `t` 在字符串 `s` 中第一次出现的位置,如果没有找到,则返回 `string::npos`。因此,如果返回值不等于 `string::npos`,说明字符串 `s` 包含字符串 `t`。
相关问题
c++判断字符串是否包含某个字符串
在C语言中,可以使用`strstr`函数来判断一个字符串是否包含另一个字符串。`strstr`函数会在源字符串中查找目标字符串,并返回第一次出现的位置指针。如果找不到目标字符串,则返回`NULL`。
下面是使用C风格字符串的示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char a[] = "abcdefghigklmn";
char b[] = "def";
char c[] = "123";
if (strstr(a, b) == NULL) {
printf("not found\n");
} else {
printf("found\n");
}
if (strstr(a, c) == NULL) {
printf("not found\n");
} else {
printf("found\n");
}
return 0;
}
```
同样地,你也可以使用C++的`string`类来进行字符串的查找操作。下面是使用C++风格字符串的示例代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string a = "abcdefghigklmn";
string b = "def";
string c = "123";
if (a.find(b) == string::npos) {
cout << "not found" << endl;
} else {
cout << "found" << endl;
}
if (a.find(c) == string::npos) {
cout << "not found" << endl;
} else {
cout << "found" << endl;
}
return 0;
}
```
判断字符串中是否包含某个字符串c++
可以使用C++中的string类的find函数来判断字符串中是否包含某个字符串。该函数返回被查找字符串在原字符串中第一次出现的位置,如果没有找到则返回string::npos。
示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world";
string subStr = "world";
if (str.find(subStr) != string::npos) {
cout << "包含子串" << subStr << endl;
} else {
cout << "不包含子串" << subStr << endl;
}
return 0;
}
```
输出结果为:
```
包含子串world
```