c语言怎么在字符串中查找指定字符串
导读:在C语言中,可以使用strstr( 函数来在一个字符串中查找另一个字符串。该函数的原型为: char *strstr(const char *haystack, const char *needle ; 其中,haystack是要查找的字...
在C语言中,可以使用strstr()函数来在一个字符串中查找另一个字符串。该函数的原型为:
char *strstr(const char *haystack, const char *needle);
其中,haystack是要查找的字符串,needle是要查找的子字符串。该函数返回子字符串在字符串中的第一个匹配位置的指针,如果未找到则返回NULL。
下面是一个示例代码:
#include stdio.h>
#include string.h>
int main() {
char str1[] = "Hello, world!";
char str2[] = "world";
char *ptr = strstr(str1, str2);
if (ptr) {
printf("'%s' found at position %ld\n", str2, ptr - str1);
}
else {
printf("'%s' not found\n", str2);
}
return 0;
}
运行结果为:
'world' found at position 7
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c语言怎么在字符串中查找指定字符串
本文地址: https://pptw.com/jishu/669736.html