C语言strstr函数的用法是什么

655Z技术栈 C/C++编程 9小时前 8

C语言中的strstr函数用于在一个字符串中查找子串的位置。

函数原型如下:

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

参数:

  • haystack:要在其中查找子串的字符串。
  • needle:要查找的子串。

返回值:

  • 如果找到了子串,返回指向子串在原字符串中第一次出现的位置的指针。
  • 如果没找到子串,返回NULL。

示例:

#include <stdio.h> #include <string.h> int main() { char str[] = "Hello, World!"; char sub[] = "World"; char *result; result = strstr(str, sub); if(result == NULL) { printf("Subtring not found!\n"); } else { printf("Substring found at index: %ld\n", result - str); } return 0; }

输出:

Substring found at index: 7

在上述示例中,我们在字符串"Hello, World!“中查找子串"World”,并找到了它在位置7处。注意,返回的指针是相对于原字符串的偏移量,可以通过减去原字符串的指针来得到子串在原字符串中的索引。如果没找到子串,返回NULL。

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

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

用微信“扫一扫”