您的位置:首页 > 其它

一天一个CRT函数 strstr

2010-04-16 17:26 399 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: