C++如何计算字符串在数据中出现的次数
我想测量以下两件事:
- 逗号出现在 a 中的次数 std::std,例如如果
str ="1,2,3,4,1,2,"
如果出现上述情况,则str.Count(',')
返回我6
string - 第二件事也类似 第一个但不是单个 char 我想计算数字 字符串出现的次数,例如
str.FindAllOccurancesOF("1,2,")
返回我2
C++ 中是否有任何内置函数用于计算此值,或者我需要为此编写自定义代码?
I want to measure the following two things:
- How many times a comma appears in a
std::std, e.g. ifstr ="1,2,3,4,1,2,"
thenstr.Count(',')
returns me6
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.gstr.FindAllOccurancesOF("1,2,")
returns me2
Is there any builtin functions in c++ for calculating this or i need to write custom code for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
关于第一个 -
编辑:
使用string::find< /a> -
IdeOne 结果
Regarding the first one -
Edit :
Using string::find -
IdeOne results
使用 std::string::find 方法之一,您可以单步执行引用字符串,并在每次找到子字符串时进行计数。无需复制或擦除。另外,使用
std::string::npos
来检查是否已找到模式,而不是文字-1
。此外,使用子字符串的大小std::string::size()
可以避免对步长进行硬编码(其他答案中的文字4
)编辑:此函数不允许重叠,即在字符串
"AAAAAAAA"
中搜索子字符串"AA"
的结果是4
。为了允许重叠,应将此行替换为
这将导致计数为
7
。问题中没有正确指定所需的行为,因此我选择了一种可能性。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 (literal4
in other answers)EDIT: This function does not allow for overlaps, i.e. searching for sub-string
"AA"
in string"AAAAAAAA"
results in a count of4
. To allow for overlap, this lineshould be replaced by
This will result in a count of
7
. The desired behaviour isn't properly specified in the question, so I chose one possibility.如果您使用
char*
(C 风格)字符串,则可以尝试以下操作(伪代码):对于出现的字符进行计数:
对于出现的字符串进行计数:
If you are using
char*
(C-style) string then following can be tried (pseudo code):For counting character occurred:
For counting string occurred:
string::find() 将开始你的旅程。
string::find() will start you on your way.