Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/145.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;如何计算字符串在数据中出现的时间_C++_Stdstring - Fatal编程技术网

C++ C++;如何计算字符串在数据中出现的时间

C++ C++;如何计算字符串在数据中出现的时间,c++,stdstring,C++,Stdstring,我想衡量以下两个方面: 逗号在表格中出现多少次 std::std,例如如果str=“1,2,3,4,1,2,” 然后str.Count(',')在上述情况下返回我6 串 第二件事也类似于 第一个,但不是单一的 我想计算一下这个数字 指字符串的出现,例如 str.FindAllOccurancesOF(“1,2,”) 返回我2 在C++中是否有任何内置函数用于计算这一点,或者我需要为此编写自定义代码?< p>如果您使用的是 char */code >(C样式)字符串,则可以尝试以下步骤(伪代码

我想衡量以下两个方面:

  • 逗号在表格中出现多少次 std::std,例如如果
    str=“1,2,3,4,1,2,”
    然后
    str.Count(',')
    在上述情况下返回我
    6
  • 第二件事也类似于 第一个,但不是单一的 我想计算一下这个数字 指字符串的出现,例如
    str.FindAllOccurancesOF(“1,2,”)
    返回我
    2

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

< p>如果您使用的是 char */code >(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 ++;
发生计数字符串的错误:

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 ++;

将开始您的旅程。

关于第一个-

std::string str="1,2,3,4,1,2," ;
std::count( str.begin(), str.end(), ',' ) ; // include algorithm header
编辑:

使用-

#包括
#包括
使用名称空间std;
int main()
{
字符串str1=“1,2,3,1,2,1,2,2,1,2,”;
字符串str2=“1,2,”;
整数计数=0;
int pos=-4;
而((pos=str1.find(str2,pos+4))!=-1)/+4,因为对于下一个
//发现迭代电流
//顺序应该取消
{
++计数;
}

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

编辑:此功能不允许重叠,即在字符串
“AAAAAAAA”
中搜索子字符串
“AA”
会导致计数
4
。要允许重叠,请使用此行

pos += step
应该由

++pos

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

为什么要删除?为什么不从当前位置+1进行查找-您的方式效率极低。@Rikardo-感谢您提高了我的效率:)您不能将该位置转发到在e模式中,您必须构建一个前缀表kmp样式,或者只从下一个位置开始查找当前位置的aka+1。第二个有几种解决方案,您必须确定实际发生的情况。str.FindAllOccurancesOf(“AAA”)的结果是什么;
?@Bo Persson Nice Catch但在我们的例子中,模式中必须包含两个或多个元素,例如“1,2”,形成模式,因为它至少包含两个元素(即1和2),但“1”没有形成一个模式,因为它只包含一个元素。我认为@Bo的意思是,如果你在
“aaaaaaa”
中计算“AA”的出现次数,那么你必须定义想要的行为。答案应该是4(无重叠)还是7(有重叠)?你不能根据模式的大小向前移动,想想“aaaa”或“abcabc”形式的模式等等-不确定为什么选择这个解决方案是正确的。@Rikardo,它通过了我的测试,但可能我遗漏了一些东西。你能给我一个字符串和子字符串的例子吗?我对CPP很陌生,有人能解释为什么pos=referenceString.find(subString,pos))?这是我唯一感到困惑的代码部分。