c语言中strchr()和strstr()函数怎么使用

   2025-02-15 5660
核心提示:在C语言中字符串处理函数`strchr()`或`strstr()`用于在字符串中查找特定字符或子字符串的位置。以下是这两个函数的基本用法:1、

在C语言中字符串处理函数`strchr()`或`strstr()`用于在字符串中查找特定字符或子字符串的位置。

以下是这两个函数的基本用法:

1、strchr()

#include char *strchr(const char *str, int c);

该函数在给定的字符串`str`中查找第一个出现的字符`c`,并返回其指针。如果未找到,则返回`NULL`。

例如:

#include #include int main() {    const char *str = "Hello, world!";    char *position = strchr(str, 'o');        if (position != NULL) {        printf("Found at position: %ld\n", position - str);    } else {        printf("Not found!\n");    }        return 0;}

2、strstr()

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

该函数在给定的字符串`haystack`中查找第一次出现的子字符串`needle`,并返回其指针。如果未找到,则返回`NULL`。

例如:

#include #include int main() {    const char *str = "Hello, world!";    char *position = strstr(str, "world");        if (position != NULL) {        printf("Found at position: %ld\n", position - str);    } else {        printf("Not found!\n");    }        return 0;}

请注意,这些函数在找到匹配项时返回指向字符串中的位置的指针,并且返回的位置是相对于原始字符串起始位置的偏移量。

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