string字符串判断是否包含char*字符串的代码
时间: 2023-10-09 12:05:24 浏览: 54
可以使用 C++ 的标准库函数 `std::string::find` 来判断一个字符串是否包含另一个字符串,示例代码如下:
```c++
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello world";
const char* str2 = "world";
if (str1.find(str2) != std::string::npos) {
std::cout << "str1 contains str2" << std::endl;
} else {
std::cout << "str1 does not contain str2" << std::endl;
}
return 0;
}
```
在上面的代码中,我们使用 `std::string::find` 函数来查找 `str2` 是否在 `str1` 中出现。如果 `find` 返回的不是 `std::string::npos`,则表示 `str2` 存在于 `str1` 中,否则 `str2` 不存在于 `str1` 中。
相关问题
c++ 判断char* 中是否含有string中的字符串
可以使用标准库中的strstr函数,该函数会在char*字符串中搜索是否含有另一个字符串string,如果有则返回该字符串首次出现的位置,如果没有则返回NULL。以下是一个示例代码:
```C
#include <stdio.h>
#include <string.h>
int main() {
char* str = "This is a string";
char* substr1 = "is";
char* substr2 = "not";
if (strstr(str, substr1) != NULL) {
printf("'%s' is found in '%s'\n", substr1, str);
} else {
printf("'%s' is not found in '%s'\n", substr1, str);
}
if (strstr(str, substr2) != NULL) {
printf("'%s' is found in '%s'\n", substr2, str);
} else {
printf("'%s' is not found in '%s'\n", substr2, str);
}
return 0;
}
```
输出结果为:
```
'is' is found in 'This is a string'
'not' is not found in 'This is a string'
```
string字符串判断是否包含某个字符
好的,关于字符串判断是否包含某个字符,可以使用string中的find()函数。该函数返回被查找字符的第一个匹配位置,如果未找到,则返回string::npos。
例如,以下代码可以用来判断字符串是否包含某个字符:
```c++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "hello world";
char c = 'o';
size_t found = str.find(c);
if (found != string::npos){
cout << "字符'" << c << "'在字符串中出现了" << endl;
}
else{
cout << "字符'" << c << "'在字符串中未出现" << endl;
}
return 0;
}
```
以上代码中,我们先定义了一个字符串"hello world",然后定义了一个要查找的字符'o',使用string的find()方法查找该字符,并将返回值存储在found中。如果返回的值不为string::npos,则表示查找到了该字符,输出包含该字符的提醒信息;否则,输出不包含该字符的提醒信息。
希望可以解答您的问题,如有不明白的地方,请随时问我。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)