【问题标题】:Finding a substring of multiple occurences in a string [C++]在字符串中查找多次出现的子字符串 [C++]
【发布时间】:2009-12-03 10:32:17
【问题描述】:

是否有任何 STL 算法或标准方法来查找特定子字符串在字符串中出现的次数?例如在字符串中:

'How do you do at ou'

字符串“ou”出现两次。我尝试了一些带有和不带有谓词的 STL 算法,但我发现来自 STL 的那些算法想要比较字符串的组件,在我的情况下是 char 但不能?比较子串。 我想出了这样的事情:

str - 字符串

obj - 我们正在寻找的子字符串

std::string::size_type count_subs(const std::string& str, const std::string& obj)
{
std::string::const_iterator beg = str.begin();
std::string::const_iterator end = str.end();
std::string::size_type count = 0;
while ((beg + (obj.size() - 1)) != end)
{
    std::string tmp(beg, beg + obj.size());
    if (tmp == obj)
    {
        ++count;
    }
    ++beg;
}
return count;
}

谢谢。

【问题讨论】:

    标签: string substring


    【解决方案1】:
    #include <string>
    #include <iostream>
    
    int Count( const std::string & str, 
               const std::string & obj ) {
        int n = 0;
        std::string ::size_type pos = 0;
        while( (pos = obj.find( str, pos )) 
                     != std::string::npos ) {
            n++;
            pos += str.size();
        }
        return n;
    }
    
    int main() {
        std::string s = "How do you do at ou";
        int n = Count( "ou", s );
        std::cout << n << std::endl;
    }
    

    【讨论】:

    • 问题:在字符串“oooo”中,你会计算模式“oo”两次还是三次。 (我个人会数三遍,因此 fo ++pos 而不是 pos += str.size()。)
    • 这取决于我想使用该功能的目的。从提问者自己的代码来看,他似乎想要不重叠的出现。
    • 感谢您的回答——尽管我认为存在逻辑错误——应该是 str.find(obj,pos)。无论如何,所以基本上没有办法可以使用 STL alg。像 count_if 或类似的,以避免显式循环。遗憾。我想知道来自 boost 的人是否有任何解决这个问题的方法。
    • 没有错误 - 我的版本在 obj 中搜索 str - 我稍微误读了你的代码,所以从你那里得到了相反的结果。这表明需要更好的名称,例如“needle”和“haystack”。至于避免显式循环——任何使用算法和谓词的东西实际上都是更多的代码。有时,最简单的旧 skool 解决方案可能是最好的。
    • 谢谢,喜欢你的名字——肯定会在我的代码中使用它们。
    猜你喜欢
    • 2017-05-08
    • 2015-01-28
    • 1970-01-01
    • 2011-04-21
    • 2010-12-25
    • 2020-02-21
    • 2018-08-24
    • 1970-01-01
    相关资源
    最近更新 更多