C语言在字符串A中查找字符串B
时间: 2023-09-03 20:15:44 浏览: 48
要在字符串A中查找字符串B,可以使用C语言中的strstr()函数。该函数的原型如下:
```c
char *strstr(const char *str1, const char *str2);
```
其中,str1是要查找的字符串,str2是要查找的子字符串。该函数返回的是一个指向str2在str1中第一次出现位置的指针。如果str2不在str1中出现,则返回NULL。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "hello world";
char str2[10] = "world";
char *ptr;
ptr = strstr(str1, str2);
if (ptr != NULL) {
printf("'%s' is found in '%s'\n", str2, str1);
} else {
printf("'%s' is not found in '%s'\n", str2, str1);
}
return 0;
}
```
输出结果为:
```
'world' is found in 'hello world'
```
在上面的例子中,我们定义了两个字符串str1和str2,其中str2是要查找的子字符串。然后使用strstr()函数在str1中查找str2。如果查找成功,那么函数返回一个指向str2在str1中第一次出现位置的指针,否则返回NULL。最后根据返回值判断是否查找成功,并输出结果。