侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 748 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

C库函数-strchr和strrchr

zze
zze
2024-03-25 / 0 评论 / 0 点赞 / 9 阅读 / 5681 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

strchr

函数原型:

#include <string.h>

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

功能:strchr 函数在给定的字符串 str 中查找指定字符 c 的首次出现位置,并返回该字符所在位置的指针。若找不到指定字符,则返回 NULL

参数:

  • str:指向要搜索的字符串的指针。

  • c:要查找的字符。

返回值:

  • 如果在 str 中找到字符 c,返回指向该字符在 str 中位置的指针。

  • 如果在 str 中未找到字符 c,返回 NULL

示例:

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello, World!";
    char *ptr = strchr(str, ',');
    
    if (ptr != NULL) {
        printf("Found character ',' at position %td\n", ptr - str + 1);
    } else {
        printf("Character not found in the string.\n");
    }

    return 0;
}

strrchr

函数原型:

#include <string.h>

char *strrchr(const char *str, int c);

功能:strrchr 函数与 strchr 类似,但它是从字符串末尾向前搜索,返回指定字符 c 在字符串 str 中最后一次出现的位置的指针。

参数:

  • str:指向要搜索的字符串的指针。

  • c:要查找的字符。

返回值:

  • 如果在 str 中找到字符 c,返回指向该字符在 str 中位置的指针。

  • 如果在 str 中未找到字符 c,返回 NULL

示例:

#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello, World!, Hello again!";
    char *ptr = strrchr(str, ',');
    
    if (ptr != NULL) {
        printf("Found character ',' at position %td\n", ptr - str + 1);
    } else {
        printf("Character not found in the string.\n");
    }

    return 0;
}

在这段示例中,strrchr 函数会找到字符串中最后一个逗号 , 的位置。如果字符串中有多个相同的字符,strchr 返回的是第一个匹配项,而 strrchr 返回的是最后一个匹配项。

0

评论区