c语言查找字符串中是否包含某个字符串
时间: 2024-01-02 18:03:00 浏览: 104
在C语言中,你可以使用strstr函数来查找一个字符串是否包含另一个字符串。该函数的原型如下:
```c
char *strstr(const char *haystack, const char *needle);
```
其中`haystack`表示要搜索的字符串,`needle`表示要查找的子字符串。该函数会返回指向第一次出现的子字符串的指针,如果没有找到,则返回NULL。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello, World!";
char str2[] = "World";
if (strstr(str1, str2) != NULL) {
printf("'%s' contains '%s'\n", str1, str2);
} else {
printf("'%s' does not contain '%s'\n", str1, str2);
}
return 0;
}
```
输出结果为:`'Hello, World!' contains 'World'`
相关问题
c语言判断字符串是否包含某个字
在C语言中,可以使用库函数strstr来判断一个字符串是否包含某个字。该函数的原型如下:
```c
#include <string.h>
char* strstr(const char* str1, const char* str2);
```
其中str1是要搜索的字符串,str2是要查找的字。该函数返回一个指针,指向str2在str1中第一次出现的位置,如果找不到则返回NULL。
以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello, world!";
char str2[] = "world";
if (strstr(str1, str2)) {
printf("字符串包含指定的字\n");
} else {
printf("字符串不包含指定的字\n");
}
return 0;
}
```
输出结果为:"字符串包含指定的字"
C语言查找某个字符在字符串数组中的位置
您可以使用C语言中的`strchr()`函数来查找某个字符在字符串中的位置。`strchr()`函数的原型如下:
```c
char *strchr(const char *str, int c);
```
其中,`str`是要查找的字符串,`c`是要查找的字符。如果找到了该字符,则返回其在字符串中的位置的指针;否则返回`NULL`。
如果你要查找某个字符在一个字符串数组中的位置,可以使用下面的代码示例:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char *str[] = {"apple", "banana", "orange", "pear", "grape"};
int n = sizeof(str) / sizeof(str[0]);
char c = 'a';
int i, j;
for (i = 0; i < n; i++) {
j = 0;
while (str[i][j] != '\0') { // 遍历当前字符串
if (str[i][j] == c) { // 如果找到了该字符
printf("%c is found in %s at position %d.\n", c, str[i], j);
}
j++;
}
}
return 0;
}
```
这个程序可以遍历字符串数组中的每一个字符串,查找其中是否包含指定的字符,并输出其在字符串中的位置。
相关推荐
![](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)