代码之家  ›  专栏  ›  技术社区  ›  jkeys

比较字符串大小是比较字符的可接受替代方案吗?

  •  0
  • jkeys  · 技术社区  · 17 年前

    std::string grep(std::string originalStr, std::string searchStr)
    {
    std::string grepStr = "";
    std::string finalStr = "";
    //stores final string; is the return value
    finalStr.resize(originalStr.length() + 1);
    grepStr.resize(originalStr.length() + 1);
    
    int place = 0;
    //remember where you are in originalStr[place]
    int numOfOccurences = 0;
    //remember number of times searchStr was found;
    //not necessary
    std::string tempStr = "";
    //will temporarily hold grepStr    
    
    //handles case if first occurence is a space
    if (originalStr[0] == ' ')
    {
        place++;
    }
    
    while (place != originalStr.length())
    {
        tempStr = "";
    
        while (originalStr[place] != ' ')
        {
    
            if (originalStr[place] == ' ')
            {
               break;
            }
    
            grepStr[place] = originalStr[place];
            ++place;
        }
    
        ++place;//ensures you skip over the space next pass
    
        for (int i = 0; i != grepStr.length(); i++)
        {
            if (grepStr[i] == searchStr[i])
            {
                //if they are the same, append that char..
                tempStr[i] = grepStr[i];
    
                if (tempStr.length() == grepStr.length())
                //..then check for string length; if same, searchStr equals tempStr
                //and you can append grepStr to the finalStr
                {                    
                    for (int x = 0; x != finalStr.length(); x++)
                    {
                        finalStr[x] = grepStr[x];
                    }
    
                    ++numOfOccurences;
                    //add one to the number of occurences in originalStr
                    finalStr += ' ';
                    //add a space IF you find the string
                }
            }
        }
    }
    
    return finalStr;
    }
    
    2 回复  |  直到 17 年前
        1
  •  4
  •   Charlie Martin    17 年前

    不,一点也不差。毕竟,至少在某些意义上,如果两个字符串的长度不相等,它们就不可能相等。

    为了度过一段美好的时光,请看看Boyer-Moore字符串匹配算法和Knuth Pratt-Morris算法。J(原文如此!他真的是这样拼写的)摩尔有一个 nice page 在他们身上。

        2
  •  0
  •   jmucchiello    17 年前

    如果你使用std::string,STL find函数可能会比你创建的这个版本运行得更高效。在字符串中搜索子字符串是一个已知的问题,我相信库版本已经尽可能地优化了。