C++ 如何计算字符串在数据中出现的次数
C++ How to calculate the number time a string occurs in a data
我想测量以下两件事:
- 逗号在std::std,例如 if
str ="1,2,3,4,1,2,"
那么str.Count(',')
在上述情况下6
返回我字符串 - 第二件事也类似于第一个打开,而不是单个我想计算数字的字符字符串的出现次数,例如
str.FindAllOccurancesOF("1,2,")
还给我2
c++ 中是否有任何内置函数来计算这个,或者我需要为此编写自定义代码?
关于第一个 -
std::string str="1,2,3,4,1,2," ;
std::count( str.begin(), str.end(), ',' ) ; // include algorithm header
编辑:
使用字符串::查找 -
#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 结果
使用 std::string::find 方法之一,可以单步执行引用字符串,每次找到子字符串时计数。无需复制或擦除。此外,使用 std::string::npos
检查是否已找到模式,而不是文字-1
。此外,使用子字符串的大小 std::string::size()
避免对步长进行硬编码(其他答案中的文字4
)
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;
}
编辑:此功能不允许重叠,即在字符串"AAAAAAAA"
中搜索子字符串"AA"
会导致计数4
。为了允许重叠,此行
pos += step
应替换为
++pos
这将导致计数为 7
。问题中没有正确指定所需的行为,所以我选择了一种可能性。
如果您使用的是char*
(C 样式)字符串,则可以尝试以下(伪代码):对于出现的字符计数:
const char *str ="1,2,3,4,1,2,", *p = str - 1;
int count = 0
while(0 != (p = strchr(++p, ',')))
count ++;
对于发生的计数字符串:
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() 将带您上路。
相关文章:
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- 具有多个模板的模板函数,用于特定数据类型(如字符串)?
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 将字符串与文件上的数据进行比较
- 如何在C++中将十六进制字符串转换为文本数据
- 如何解析表示树状数据结构的字符串
- 为什么字符串的 move() 会改变内存中底层数据的位置?
- 将收到的 usart uint8_t* 数据与常量字符串进行比较
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何避免将数据缓冲区的额外副本复制到字符串?
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 在 MFC 中使用 strncpy() 复制字符串时截断的数据
- 利用输入文件中的数据(字符串和int)并在循环中利用
- 如何用 c++ 读取 txt 文件,如果我们不知道其中有多少个数据字符串,以及每行有多长?
- 将数据(字符串或整数)添加到 char 数组
- 从文本文件到实际十六进制的文本十六进制数据字符串
- 如何将流数据(字符串)解析为不同的数据文件
- 当绕过c++中的函数从目标进程的ExtTextOut复制数据字符串时,malloc会导致崩溃吗?
- 如何将数据(字符串、整数或枚举成员)与Gtk::ComboBoxText项关联?