一天一個CRT函數 strchr

又過了好多天沒有寫這個系列了,哎,懶惰啊!今天太鬱悶了,早上騎車上班時,被一輛小車突然打開的車門給絆倒了,還摔得不輕!

strchr

1.介紹

MSDN上給出的解釋是,找出字符串中指定的字符,返回第一個找到的字符位置的指針(即地址),如果沒有找到則返回NULL。

   1: /***
   2: char *strchr(string, chr) - search a string for a character
   3:     
   4: Purpose:
   5:        Searches a string for a given character, which may be the
   6:            null character '/0'.
   7: Entry:
   8:        char *string - string to search in
   9:            char chr     - character to search for
  10:     
  11: Exit:
  12:        returns pointer to the first occurence of c in string
  13:            returns NULL if chr does not occur in string
  14: ***/
  15: template<typename T> 
  16: inline tChar *tStrChr(tChar *pStr, T chr)
  17: {
  18:     while( *pStr && *pStr != chr )
  19:         ++pStr;
  20:  
  21:     if( *pStr == chr )
  22:         return(pStr);
  23:  
  24:     return 0;
  25: }

很簡單,就是循環遍歷字符串,然後與指定的字符相比較。

2.測試

   1: tChar  ch = _T('r');
   2:  
   3:     tChar string[] = _T("The quick brown dog jumps over the lazy fox");
   4:  
   5:     // Search forward. 
   6:     tChar *pdest = CY_CRT::tStrChr( string, ch );
   7:     int result = (int)(pdest - string + 1);
   8:  
   9:     if ( pdest != NULL )
  10:         wcout << _T("Result:   first ") << ch << _T(" found at position ") << result << endl;
  11:     else
  12:         cout << "Result: " <<  result << "found/n";

3.兄弟函數

strrchr,這就是strchr的兄弟,不過卻是反向尋找字符串中指定字符

   1: template<typename T> 
   2: inline tChar *tStrRChr(tChar *pStr, T chr)
   3: {
   4:     tChar *pStart = pStr;
   5:  
   6:     while(*pStr++)                     
   7:         ;
   8:     while(--pStr != pStart && *pStr != chr)
   9:         ;
  10:  
  11:     if( *pStr == chr )            
  12:         return pStr;
  13:  
  14:     return 0;
  15: }

說明:先找到把指定的字符串的結尾,然後倒序遍歷字符串與指定字符的比較。

3.總結

我還是喜歡用C++標準庫提供的模板函數(可以配合容器,當然數組也是容器的一個特化),上述的功能對應了STL提供的find_first_of,配合reverse_iterator就是反向查找(strrchr)。而string提供了find_last_of方法,所以字符串操作用string類是很方便的事情。

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