C++ 判断一个大字符串里出现一个小字符串的次数 string对象
怪我咯
怪我咯 2017-04-17 11:46:58
0
3
556

C++ 如何判断一个大字符串里出现一个小字符串的次数 用string对象的自带函数有吗

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(3)
Peter_Zhu

Encapsulate the find method.

Handwritten sample code for reference only:

cppstd::string str("abcabdabcdsdabcds");

auto occurrences = [&str](const std::string &dest) {
    size_t pos, pre = 0, count = 0;
    while ( (pos = str.find(dest, pre)) != std::string::npos ) {
        ++count;
        pre = pos + 1;
    }
    return count;
};

std::cout << occurrences("abc") << std::endl;
洪涛

Write an example, such as the number of times abc appears in abcabcabcdsadg

刘奇

It can be processed using KMP algorithm or Sunday algorithm

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template