首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在C中查找字符串中子字符串的位置

在C语言中,可以使用strstr()函数来查找字符串中子字符串的位置。strstr()函数是C语言标准库中的字符串处理函数,它的原型如下:

代码语言:c
复制
char *strstr(const char *haystack, const char *needle);

其中,haystack是要搜索的字符串,needle是要查找的子字符串。如果找到子字符串,strstr()函数会返回一个指向子字符串第一个字符的指针,否则返回NULL。

以下是一个简单的示例代码,演示如何使用strstr()函数查找字符串中子字符串的位置:

代码语言:c
复制
#include<stdio.h>
#include<string.h>

int main() {
    char haystack[] = "This is a sample string.";
    char needle[] = "sample";
    char *result;

    result = strstr(haystack, needle);
    if (result != NULL) {
        printf("Substring found at position %ld\n", result - haystack);
    } else {
        printf("Substring not found\n");
    }

    return 0;
}

在这个示例中,我们在字符串"This is a sample string."中查找子字符串"sample",输出结果为"Substring found at position 10",表示子字符串"sample"在字符串"This is a sample string."中的位置是第10个字符。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券