一天一個CRT函數 strstr

1.介紹

char *strstr( const char *str, const char *strSearch );

需找str字符串中出現strSearch字符串位置的指針。如果沒找到,則返回NULL,如果strSearch爲空,則返回str。

2.實現

inline tChar *tStrStr(tChar *pStr, tChar *pSubStr)
{
/* First scan quickly through the two strings looking for a
* single-character match. When it's found, then compare the
* rest of the substring.
*/

tChar *b = pSubStr;
if( *b == NULL )
{
return pStr;
}

tChar *a = NULL;
for( ; *pStr != NULL; pStr++)
{
if( *pStr != *b )
{
continue;
}

a = pStr;
while(1)
{
if( *b == NULL )
{
return pStr;
}
if( *a++ != *b++ )
{
break;
}
}

b = pSubStr;
}

return NULL;
}
其實,也就是雙重循環比較。
 
3.測試
tChar str[] =    _T("lazy");
tChar string[] = _T("The quick brown dog jumps over the lazy fox");

tChar *pdest = NULL;
int result = 0;

pdest = CY_CRT::tStrStr( string, str );
result = (int)(pdest - string + 1);


4.後記
CRT提供了strstr外,還有strrstr,即反序查找。
當然,STL裏也有提供類似的算法—find_fist_of/find_last_of/find_first_not_of/find_last_not_of.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章