【庫函數源碼剖析系列】(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。


 

發佈了80 篇原創文章 · 獲贊 11 · 訪問量 34萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章