C++如何计算字符串在数据中出现的次数 [英] C++ How to calculate the number time a string occurs in a data

查看:71
本文介绍了C++如何计算字符串在数据中出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想衡量以下两点:

  • 逗号在std::std,例如如果 str ="1,2,3,4,1,2,"然后 str.Count(',') 在上述情况下返回我 6字符串
  • 第二件事也类似第一个但不是单身我想计算数字的字符字符串出现的次数,例如str.FindAllOccurancesOF("1,2,")返回我 2
  • 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

C++ 中是否有任何内置函数来计算这个,或者我需要为此编写自定义代码?

Is there any builtin functions in c++ for calculating this or i need to write custom code for this?

推荐答案

使用 std::string::find 方法之一,您可以单步执行引用字符串,每次找到子字符串时进行计数.无需复制或擦除.另外,使用 std::string::npos 来检查是否找到了模式,而不是文字 -1.此外,使用子字符串的大小,std::string::size(),避免对步长进行硬编码(其他答案中的文字 4)

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:此函数不允许重叠,即在字符串 "AAAAAAAA" 中搜索子字符串 "AA" 结果为4 的计数.为了允许重叠,这条线

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

应该换成

++pos

这将导致计数 7.问题中未正确指定所需的行为,因此我选择了一种可能性.

This will result in a count of 7. The desired behaviour isn't properly specified in the question, so I chose one possibility.

这篇关于C++如何计算字符串在数据中出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆