Подсчет количества вхождений строки в строке

Каков наилучший способ подсчета всех вхождений подстроки внутри строки?

Пример: подсчет случаев Foo внутри FooBarFooBarFoo

1

Решение

Один из способов сделать это использовать std :: string find функция:

#include <string>
#include <iostream>
int main()
{
int occurrences = 0;
std::string::size_type pos = 0;
std::string s = "FooBarFooBarFoo";
std::string target = "Foo";
while ((pos = s.find(target, pos )) != std::string::npos) {
++ occurrences;
pos += target.length();
}
std::cout << occurrences << std::endl;

}
4

Другие решения

#include <iostream>
#include <string>

// returns count of non-overlapping occurrences of 'sub' in 'str'
int countSubstring(const std::string& str, const std::string& sub)
{
if (sub.length() == 0) return 0;
int count = 0;
for (size_t offset = str.find(sub); offset != std::string::npos;
offset = str.find(sub, offset + sub.length()))
{
++count;
}
return count;
}

int main()
{
std::cout << countSubstring("FooBarFooBarFoo", "Foo")    << '\n';

return 0;
}
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector