search

Home  >  Q&A  >  body text

C++ 判断一个大字符串里出现一个小字符串的次数 string对象

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

怪我咯怪我咯2803 days ago557

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 11:48:58

    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;
    

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 11:48:58

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

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 11:48:58

    It can be processed using KMP algorithm or Sunday algorithm

    reply
    0
  • Cancelreply