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

走远了吗. 提交于 2019-12-04 12:52:02

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!