2024年3月26日发(作者:)

c语言strstr函数用法

C语言strstr函数用法

简介

strstr函数是C语言中用于在一个字符串中查找子串的函数。它

的原型如下:

char *strstr(const char *haystack, const char *need

le);

该函数在字符串 haystack 中查找 needle 第一次出现的位置,

并返回指向该位置的指针。如果未找到该子串,则返回空指针。

参数解析

• haystack:要被搜索的字符串;

• needle:要搜索的子串。

用法示例

以下是几个常见的使用示例,帮助你更好地理解strstr函数的用

法。

示例1:查找子串

#include <>

#include <>

int main() {

char *str = "Hello World!";

char *result;

result = strstr(str, "World");

if (result) {

printf("找到了子串!n");

printf("子串在str中的位置是:%sn", result);

} else {

printf("未找到子串!n");

}

return 0;

}

输出结果为:

找到了子串!

子串在str中的位置是:World!

示例2:未找到子串

#include <>

#include <>

int main() {

char *str = "Hello World!";