每日学习总结20240301

20240301

1. strchr VS strrchr

strchrstrrchr是C语言标准库中的字符串处理函数,用于在字符串中查找特定字符的位置。

1.1 strchr函数

strchr函数用于在字符串中查找第一次出现指定字符的位置,并返回该位置的指针。函数原型如下:

char *strchr(const char *str, int c);
  • str:要在其中搜索的字符串。
  • c:要查找的字符的ASCII值。

strchr函数会返回一个指向第一次出现指定字符的指针。如果未找到指定字符,则返回NULL

示例用法:

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

int main() {
    char str[] = "Hello, World!";
    char *ptr = strchr(str, 'W');
    if (ptr != NULL) {
        printf("Found 'W' at position: %ld\n", ptr - str);
    } else {
        printf("Character not found.\n");
    }
    return 0;
}

输出将是:

Found 'W' at position: 7
1.2 strrchr函数

strrchr函数与strchr函数类似,但是它在字符串中从右向左查找指定字符,并返回最后一次出现的位置的指针。函数原型如下:

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

参数与strchr函数相同。

strrchr函数会返回一个指向最后一次出现指定字符的指针。如果未找到指定字符,则返回NULL

示例用法:

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

int main() {
    char str[] = "Hello, World!";
    char *ptr = strrchr(str, 'o');
    if (ptr != NULL) {
        printf("Found 'o' at position: %ld\n", ptr - str);
    } else {
        printf("Character not found.\n");
    }
    return 0;
}

输出将是:

Found 'o' at position: 8

总结:

  • strchr函数在字符串中查找第一次出现指定字符的位置。
  • strrchr函数在字符串中查找最后一次出现指定字符的位置。
  • 如果指定字符未找到,两个函数都会返回NULL

在这里插入图片描述

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值