温馨提示×

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

小亿
98
2023-11-14 16:12:45
栏目: 编程语言

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。

0