首页 > 编程笔记 > C语言函数大全 阅读:3467

C语言strstr():在字符串中查找特定子串

strstr() 是 C语言的一个标准库函数,定义在<string.h>头文件中。

strstr() 函数的功能是在某个字符串中查找第一次出现的特定字符串(子串)。该函数的原型如下:
char *strstr(const char *haystack, const char *needle);

参数

  • haystack:指向一个字符串,从此字符串中查找 needle 子串。
  • needle:要查找的子串。

返回值

如果找到子串,则该函数返回一个指针,它指向子串第一次出现的位置;反之,如果未在主字符串中找到子串,则返回 NULL。

【实例】以下 C语言代码示例说明了如何使用 strstr() 函数。
#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("The substring '%s' is found at position: %ld\n", needle, result - haystack);
 } else {
 printf("The substring '%s' was not found in the string.\n", needle);
 }
 
 return 0;
}
上述代码将在字符串 "Hello, World!" 中查找子字符串 "World",并输出其在字符串中的位置。结果为:

The substring 'World' is found at position: 7

请注意,数组索引是从 0 开始的,所以位置 7 实际上是字符串中的第八个字符。

AltStyle によって変換されたページ (->オリジナル) /