I want to measure the following two things:
str ="1,2,3,4,1,2,"
then str.Count(',')
returns me 6
in case of above
stringstr.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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With