简体   繁体   中英

How can I count number of “xxx” in string c++?

I want to count number of xxx in string s and I tried this:

cn2=count(s.begin(), s.end(), 'xxx'); and this is the problem: warning: multi-character character constant [-Wmultichar]|

then I tried this:

cn2=count(s.begin(), s.end(), "xxx");

but we should enter character in count parameters.

You can use std::string::find() in a loop, eg:

int count = 0;
std::string::size_type pos = 0;
while ((pos = s.find("xxx", pos)) != std::string::npos)
{
    ++count;
    pos += 3;
}

Or std::search() :

#include <algorithm>

int count = 0;
std::string sub = "xxx";
std::string::iterator iter = s.begin();
while ((iter = std::search(iter, s.end(), sub.begin(), sub.end())) != s.end())
{
    ++count;
    iter += sub.size();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM