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;
ask by inspite translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…