一天一个CRT函数 strstr

来源:互联网 发布:linux删除用户附加组 编辑:程序博客网 时间:2024/06/06 02:49

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.