字符串匹配实现

String matching implementation

本文关键字:实现 串匹配 字符串 字符      更新时间:2023-10-16

我写了下面的代码来检查文本中是否存在certin字符串。问题是即使文本中存在模式,match()函数也总是返回false

int main(){
    char *text="hello my name is plapla";
    char *patt="my";
    cout<<match(patt,text);
    system("pause");
    return 0;
}
bool match(char* patt,char* text){
    int textLoc=0, pattLoc=0, textStart=0;
    while(textLoc <= (int) strlen(text) && pattLoc <= (int)strlen(patt)){
        if( *(patt+pattLoc) == *(text+textLoc) ){
            textLoc= textLoc+1;
            pattLoc= pattLoc+1;
        }
        else{
            textStart=textStart+1;
            textLoc=textStart;
            pattLoc=0;
        }
    }
    if(pattLoc > (int) strlen(patt))
        return true;
    else return false;
}

while循环中尝试pattLoc < (int)strlen(patt)。循环将在pattLoc == 2时停止,因此避免将"my"''"hello my name is pala"' '进行比较,后者将pattloc设置为0return false

或者最好使用字符串substr

显而易见的解决方案是:

bool
match( std::string const& pattern, std::string const& text )
{
    return std::search( text.begin(), text.end(), 
                        pattern.begin(), pattern.end() )
            != text.end();
}

这是惯用的C++,也是我所期望的任何C++程序员至少在专业环境下写。

如果目标是学习如何编写这样的函数,那么,以上并不是一个很好的解决方案。那么解决方案应该是mroe分而治之;match太多了,你放不下在一个功能中。我推荐这样的东西:

bool
startsWith( std::string::const_iterator begin,
            std::string::const_iterator end,
            std::string const& pattern )
{
    return end - begin >= pattern.size()
        && std::equal( pattern.begin(), pattern.end(), begin );
}
bool
match( std::string const& pattern, std::string const& text )
{
    std::string::const_iterator current = text.begin();
    while ( current != text.end()
            && !startsWith( begin, text.end(), pattern ) ) {
        ++ current;
    }
    return current != text.end();
}

这显然是可以改进的;例如当剩余文本的长度为小于图案的长度。

如果你的教授坚持你使用char const*(如果他坚持在char*上,那么他完全不称职,应该被解雇)可以很容易地重写:只需将对begin的所有调用替换为指针以及对具有pointer + strlen(pointer)end的所有调用。

我已经解决了问题:

while(textLoc <= (int) strlen(text) && pattLoc <= (int)strlen(patt))

应该是:

while(textLoc < (int) strlen(text) && pattLoc < (int)strlen(patt))

以及if(pattLoc > (int) strlen(patt))if(pattLoc >= (int) strlen(patt))