Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to calculate the number time a string occurs in a data

Tags:

c++

stdstring

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?

like image 748
Jame Avatar asked Dec 02 '22 02:12

Jame


2 Answers

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

like image 103
Mahesh Avatar answered Dec 05 '22 18:12

Mahesh


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.

like image 36
juanchopanza Avatar answered Dec 05 '22 17:12

juanchopanza