【库函数源码剖析系列】(6) strchr

strchr:

// strchr
#include <stdio.h>

char *Strchr(const char *s, int c)
{
	for (; *s != (char)c; ++s) {
		if (*s == '\0') {
			return NULL;
		}
	}
	
	return (char *)s;
}

int main( int argc, char **argv )
{
	char string[] = "The quick brown dog jumps over the lazy fox";
	char fmt1[] =   "         1         2         3         4         5";
	char fmt2[] =   "12345678901234567890123456789012345678901234567890";	
	char *pdest = NULL;
	int result;
	char ch;
	printf( "String to be searched: \n\t\t%s\n", string );
	printf( "\t\t%s\n\t\t%s\n\n", fmt1, fmt2 );
	
	ch = 'r';
	printf( "Search char:\t%c\n", ch );	
	pdest = Strchr( string, ch );
	result = pdest - string + 1;
	if( pdest != NULL )
		printf( "Result:\tfirst %c found at position %d\n\n", 
		ch, result );
	else
		printf( "Result:\t%c not found\n" );
	
	ch = '\0';	// 测试特殊字符
	printf( "Search char:\t%c(此处是\'\\0\',不可显示)\n", ch );	
	pdest = Strchr( string, ch );
	result = pdest - string + 1;
	if( pdest != NULL )
		printf( "Result:\tfirst %c found at position %d\n\n", 
		ch, result );
	else
		printf( "Result:\t%c not found\n" );
	
	return 0;
}

1、当传入的指针是NULL时,函数中是没有检查的。

2、注意当查找的字符是'\0'时,应该总是找得到的!返回的是字符串尾'\0'的地址,不过想想,返回这个指针还有什么用呢?没什么实际意义啊。这一点也造成strchr函数极易写错,比如:

char *Strchr(const char *s, int c)
{
	while (*s != '\0' && *s != (char)c)
		s++;
	
	if (*s == '\0')
		return NULL;
	
	return (char *)s;
}

上面的程序是错的,就是因为当查找的是'\0'时,它认为是到达了字符串尾,却没想到'\0'使while的两个条件同时为假了!这种错误得注意。所以应改为:

char *Strchr(const char *s, int c)
{
	while (*s != '\0' && *s != (char)c)
		s++;
	
	if (*s == (char)c)
		return (char *)s;

	return NULL;
}

必须先测试是不是找到了c。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值