I want to measure the following two things:
- How many times a comma appears in a
std::std, e.g. if
str ="1,2,3,4,1,2,"
then str.Count(',')
returns me 6
in case of above
string
- The second thing is also similar to
the first on but instead of single
char i want to calculate the number
of occurances of a string e.g
str.FindAllOccurancesOF("1,2,")
returns me 2
Is there any builtin functions in c++ for calculating this or i need to write custom code for this?
Using one of the std::string::find methods, you can step through the reference string, counting each time you find the sub-string. No need for copies or erases. Also, use std::string::npos
to check whether the pattern has been found or not, instead of literal -1
. Also, using the sub-string's size, std::string::size()
, avoids hard coding the step size (literal 4
in other answers)
size_t stringCount(const std::string& referenceString,
const std::string& subString) {
const size_t step = subString.size();
size_t count(0);
size_t pos(0) ;
while( (pos=referenceString.find(subString, pos)) !=std::string::npos) {
pos +=step;
++count ;
}
return count;
}
EDIT: This function does not allow for overlaps, i.e. searching for sub-string "AA"
in string "AAAAAAAA"
results in a count of 4
. To allow for overlap, this line
pos += step
should be replaced by
++pos
This will result in a count of 7
. The desired behaviour isn't properly specified in the question, so I chose one possibility.
Regarding the first one -
std::string str="1,2,3,4,1,2," ;
std::count( str.begin(), str.end(), ',' ) ; // include algorithm header
Edit :
Using string::find -
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str1 = "1,2,3,1,2,1,2,2,1,2," ;
string str2 = "1,2," ;
int count = 0 ;
int pos = -4;
while( (pos = str1.find(str2, pos+4) ) != -1 ) // +4 because for the next
// iteration current found
// sequence should be eliminated
{
++count ;
}
cout << count ;
}
IdeOne results
If you are using char*
(C-style) string then following can be tried (pseudo code):
For counting character occurred:
const char *str ="1,2,3,4,1,2,", *p = str - 1;
int count = 0
while(0 != (p = strchr(++p, ',')))
count ++;
For counting string occurred:
const char *str ="1,2,3,4,1,2,", *p = str - 1;
int count = 0;
while(0 != (p = strstr(++p, "1,2,")))
count ++;
string::find() will start you on your way.