我正在做一些事情,我意识到我想要计算/我能在字符串中找到多少,然后它让我感到震惊,有几种方法可以做到,但无法决定最好的(或最简单的)是什么.
目前我正在做的事情如下:
string source = "/once/upon/a/time/";
int count = source.Length - source.Replace("/", "").Length;
Run Code Online (Sandbox Code Playgroud)
但我完全不喜欢它,任何接受者?
我真的不想挖掘RegEx这个,是吗?
我知道我的字符串将会有我正在搜索的术语,所以你可以认为......
当然,对于字符串,其中 长度> 1,
string haystack = "/once/upon/a/time";
string needle = "/";
int needleCount = ( haystack.Length - haystack.Replace(needle,"").Length ) / needle.Length;
Run Code Online (Sandbox Code Playgroud)