c语言

c语言怎么查找字符串中子串位置

小亿
188
2024-02-28 16:59:18
栏目: 编程语言

在C语言中,可以使用strstr函数来查找字符串中子串的位置。该函数的原型如下:

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

其中,haystack是要查找的字符串,needle是要查找的子串。函数返回子串在字符串中第一次出现的位置,如果找不到子串,则返回NULL。

下面是一个示例代码:

#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("子串出现在字符串的位置:%ld\n", result - haystack);
    } else {
        printf("未找到子串\n");
    }
    
    return 0;
}

在上面的示例代码中,我们查找子串"World"在字符串"Hello, World!“中的位置。如果找到子串,则打印子串在字符串中的位置,否则打印"未找到子串”。

0
看了该问题的人还看了