xxxxxxxxxx
string str,sub; // str is string to search, sub is the substring to search for
vector<size_t> positions; // holds all the positions that sub occurs within str
size_t pos = str.find(sub, 0);
while(pos != string::npos)
{
positions.push_back(pos);
pos = str.find(sub,pos+1);
}
xxxxxxxxxx
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s("hello hello");
int count = 0;
size_t nPos = s.find("hello", 0); // first occurrence
while(nPos != string::npos)
{
count++;
nPos = s.find("hello", nPos + 1);
}
cout << count;
};
xxxxxxxxxx
void countCharImproved(char *str) {
std::map<char, int> count;
int l = strlen(str);
for(int i=0; i<l; i++) {
count[str[i]]++;
}
for(const auto kvp : count) {
std::cout << kvp.first << " occurs " << kvp.second << " times\n";
}
}