【庫函數源碼剖析系列】(6) strchr

來源:互聯網
上載者:User

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 );elseprintf( "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 );elseprintf( "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。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.