c语言中的strstr函数怎么使用

655Z技术栈 C/C++编程 2026年01月06日 9

strstr函数用于在一个字符串中查找另一个字符串第一次出现的位置。函数原型如下:

char *strstr(const char *haystack, const char *needle);

其中,haystack表示要查找的字符串,needle表示要搜索的子字符串。

使用方法如下:

#include <stdio.h> #include <string.h> int main() { const char *haystack = "Hello, world!"; const char *needle = "world"; char *result = strstr(haystack, needle); if (result) { printf("'%s' found at position %ld\n", needle, result - haystack); } else { printf("'%s' not found\n", needle); } return 0; }

以上代码将在haystack中查找needle,如果找到则输出其位置,否则输出未找到的信息。

提供PHP及ThinkPHP框架的定制开发、代码优化,PHP修改、ThinkPHP修改。

邮箱:yvsm@163.com 微信:yvsm316 QQ:316430983
关闭

用微信“扫一扫”