strstr函数
strstr函数是C语言中的一个字符串函数,用于在一个字符串中查找另一个字符串的出现位置。
它的函数原型如下:
char *strstr(const char *haystack, const char *needle);
在这个函数中,haystack表示被搜索的字符串,needle表示要查找的子字符串。函数的返回值是一个指针,指向第一次出现needle的位置,如果没有找到,返回NULL。
例如,我们可以使用strstr函数来查找一个字符串中是否包含另一个字符串:
#include <stdio.h>
#include <string.h>
int main() {
char haystack[] = "Hello, world!";
char needle[] = "world";
char *result = strstr(haystack, needle);
if (result != NULL) {
printf("'%s' is found in '%s' at position %ld.\n", needle, haystack, result - haystack);
} else {
printf("'%s' is not found in '%s'.\n", needle, haystack);
}
return 0;
}
上述代码输出为:
'world' is found in 'Hello, world!' at position 7.
需要注意的是,strstr函数是区分大小写的,如果要进行大小写不敏感的查找,可以使用其他函数,例如strcasestr。
使用示例
查找子字符串成功后,用strncpy修改内存块内容。
#include <stdio.h>
#include <string.h>
#include<assert.h>
int main()
{
char str[] = "This is a simple string hello world!";
char* pch;
pch = strstr(str, "string");
if (pch != NULL)
{
printf("%s\n",str);
printf("%s\n",pch);
strncpy(pch, "sifang",6);
}
printf("%s\n",str);
printf("%s\n",pch);
return 0;
}
输出结果:
由输出的结果可知,pch的内容为str的子字符串,指向