我想衡量以下两点:C++如何计算数量的时间在数据发生串
- 多少次逗号出现在 的std ::性病,如如果
str ="1,2,3,4,1,2,"
然后str.Count(',')
返回我6
在上述 串 - 情况下,第二件事情也类似于 第一上,但不是单一的 字符我要计算一个字符串如的出现的次数
str.FindAllOccurancesOF("1,2,")
返回我2
C++中是否有任何内置函数用于计算此值,或者我需要为此编写自定义代码?
我想衡量以下两点:C++如何计算数量的时间在数据发生串
str ="1,2,3,4,1,2,"
然后str.Count(',')
返回我6
在上述 串str.FindAllOccurancesOF("1,2,")
返回我2
C++中是否有任何内置函数用于计算此值,或者我需要为此编写自定义代码?
使用的std ::一个字符串::找方法,你可以一步通过引用字符串,每次找到子字符串时计数。无需复制或删除。此外,使用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;
}
编辑:此功能不允许重叠,即寻找子串"AA"
在字符串"AAAAAAAA"
导致计数4
。为了允许重叠,该行
pos += step
应
++pos
这种替代将导致7
计数。问题中没有正确指定所需的行为,所以我选择了一种可能性。
你不能通过模式的大小向前移动,考虑形式“aaaa”或“abcabc”等模式。 - 不知道为什么选择这个解决方案是正确的。 – 2011-05-21 01:17:11
@ Rikardo,它通过我的测试,但也许我错过了一些东西。你能给我一个它不起作用的字符串和子字符串的例子吗? – juanchopanza 2011-05-21 08:06:57
如果您正在使用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()将启动你的方式。
关于第一个 -
std::string str="1,2,3,4,1,2," ;
std::count(str.begin(), str.end(), ',') ; // include algorithm header
编辑:
使用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 ;
}
你为什么擦掉?为什么不直接从当前位置+1找到 - 你的方式是疯狂的低效率。 – 2011-05-20 06:46:14
@Rikardo - 感谢提高我的效率:) – Mahesh 2011-05-20 07:37:36
你不能通过模式的大小转发位置,你必须建立一个前缀表kmp风格,或者只是从下一个位置向前找到aka +1从当前位置。 – 2011-05-21 01:15:56
第二个有几个解决方案,你将不得不决定实际发生的是什么。 'str =“AAAAAAAAAA”的结果是什么? str.FindAllOccurancesOf( “AAA”);'? – 2011-05-20 06:56:24
@Bo Persson Nice Catch但在我们的例子中,模式必须包含两个或多个元素,例如“1,2”形成一个模式,因为它包含至少两个元素(即1和2),但“1”不形成模式因为它只包含单个元素 – Jame 2011-05-20 07:25:46
我认为@Bo意味着您必须定义想要的行为,以便计算在“AAAAAAAA”'中出现“AA”''的情况。答案是4(不重叠)还是7(重叠)? – juanchopanza 2011-05-21 09:07:47