(standard c libraries translation )strchr

strchr, strrchr, strchrnul - locate character in string
strchr,strrchr,strchrnul-定位字符串中的字符

所需头文件
#include <string.h>

char *strchr(const char *s, int c);
char *strrchr(const char *s, int c);

#define _GNU_SOURCE         /* See feature_test_macros(7) */
#include <string.h>
char *strchrnul(const char *s, int c);

The strchr() function returns a pointer to the first occurrence of the character c in the string s.
The strrchr() function returns a pointer to the last occurrence of the character c in the string s.
The  strchrnul()  function is like strchr() except that if c is not found in s, then it returns a pointer to the null byte at the end of s, rather than NULL. Here "character" means "byte"; these functions do not work with wide or multibyte characters.
strchr()函数返回指向字符串s中第一个找到的的字符c的指针
strrchr()函数返回指向字符串s中最后一个找到的字符c的指针
strchrnul()函数跟strchr类似,除了如果在s中无法找到字符c,返回指向字符串s结尾的null字节,而不是NULL,这里的字符意思是字节,这些函数针对宽字符或者多字节字符是有问题的

返回值
The strchr() and strrchr() functions return a pointer to the matched character or NULL if the character is not found.  The  terminating  null  byte  is considered part of the string, so that if c is specified as '\0', these functions return a pointer to the terminator.
The strchrnul() function returns a pointer to the matched character, or a pointer to the null byte at the end of s (i.e., s+strlen(s)) if the character is not found.
strchr()和strrchr()函数返回一个指向匹配字符的指针,如果没有找到则返回NULL,字符结束符null字节看作是字符串的一部分,如果c的值是\0,这些函数返回指向字符结尾的指针,

strchrnul函数返回一个指向匹配字符的指针,如果没有找到则返回s尾部的null字节。


testcast如下:

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

int main(void)
{
	const char *s = "abcdefabc";
	int c = 'b';
	char *tmp = NULL;
	
	tmp = strchr(s, c);
	printf("tmp = %s\n", tmp);
	
	tmp = strrchr(s, c);
	printf("tmp = %s\n", tmp);

	tmp = strchrnul(s, 'x');
	printf("tmp = %s\n", tmp);
	return 0;
}

测试结果如下:

cheny.le@cheny-ThinkPad-T420:~/cheny/testCode$ ./a.out
tmp = bcdefabc
tmp = bc
tmp =

最后一个tmp的结果是空(也就是nul),但是不是NULL,这个需要注意,关于nul,NULL和\0的区别以前文章有讲,不要搞混淆了哈

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值