#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;
};
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);
}
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
";
}
}
Code Example |
---|
Cpp :: slice a vector c++ |
Cpp :: How to get cursor position c++ |
Cpp :: position of max element in vector c++ |
Cpp :: c++ compile to exe |
Cpp :: print counting in c++ |
Cpp :: c++ thread |
Cpp :: demonstrate constructor |
Cpp :: cpp vector |
Cpp :: how to initialize 2d array with values c++ |
Cpp :: cpp define function |
Cpp :: cpp map insert |
Cpp :: function overriding in c++ |
Cpp :: vectors c++ |
Cpp :: reverse an array in c++ stl |
Cpp :: c++ template |
Cpp :: run c++ program mac |
Cpp :: do while c++ |
Cpp :: substring in c++ |
Cpp :: c++ loop trhought object |
Cpp :: C++ program for Celsius to Fahrenheit and Fahrenheit to Celsius conversion using class |
Cpp :: draw line sfml |
Cpp :: initialize 2d vector c++ |
Cpp :: three way comparison operator c++ |
Cpp :: call function from separate bash script |
Cpp :: array 2d to 1d |
Cpp :: len in cpp |
Cpp :: cpp undefined reference to function |
Cpp :: free a pointer c++ |
Cpp :: hashset in cpp |
Cpp :: even and odd numbers 1 to 100 |