您如何计算字符串中字符串(实际上是字符)的出现?

前提是你 提交于 2020-08-15 10:54:27

问题:

I am doing something where I realised I wanted to count how many / s I could find in a string, and then it struck me, that there were several ways to do it, but couldn't decide on what the best (or easiest) was. 我正在做某件事,我意识到我想计算一个字符串中可以找到多少个/秒,然后让我感到震惊的是,有几种方法可以做到,但无法决定最好的(或最简单的)是。

At the moment I'm going with something like: 目前,我正在处理类似:

string source = "/once/upon/a/time/";
int count = source.Length - source.Replace("/", "").Length;

But I don't like it at all, any takers? 但是,我一点都不喜欢它,对吗?

I don't really want to dig out RegEx for this, do I? 我真的不想为此挖掘RegEx ,对吗?

I know my string is going to have the term I'm searching for, so you can assume that... 我知道我的字符串将包含我要搜索的术语,因此可以假定...

Of course for strings where length > 1 , 当然,对于其中的字符串长度> 1,

string haystack = "/once/upon/a/time";
string needle = "/";
int needleCount = ( haystack.Length - haystack.Replace(needle,"").Length ) / needle.Length;

解决方案:

参考一: https://stackoom.com/question/2GzC/您如何计算字符串中字符串-实际上是字符-的出现
参考二: https://oldbug.net/q/2GzC/How-would-you-count-occurrences-of-a-string-actually-a-char-within-a-string
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!