c语言strstr函数的作用是什么

1564
2024/2/11 11:29:25
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C语言中,strstr函数用于在一个字符串中查找另一个字符串第一次出现的位置。该函数的原型如下:

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

其中,haystack是要查找的字符串,needle是要查找的子字符串。该函数会返回一个指向第一次出现needle的位置的指针,如果未找到则返回NULL。

例如,如果有字符串"hello world",要查找其中是否包含字符串"world",可以使用strstr函数:

char *result = strstr("hello world", "world");
if (result != NULL) {
    printf("Found at position: %ld\n", result - "hello world");
}

上述代码会输出Found at position: 6,表示在字符串"hello world"中找到了子字符串"world",并且是从位置6开始的。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c语言怎么打印输出三角形