现在的位置: 首页 > 综合 > 正文

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

2013年08月26日 ⁄ 综合 ⁄ 共 1238字 ⁄ 字号 评论关闭

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。

 

【上篇】
【下篇】

抱歉!评论已关闭.