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

   2025-02-15 6860
核心提示:C语言中的strstr函数用于在一个字符串中查找子串的位置。函数原型如下:char *strstr(const char *haystack, const char *needle

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。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言