我正在做一些事情,我意识到我想要在一个字符串中找到多少个/s,然后我突然想到,有几种方法可以做到这一点,但不能决定哪种是最好的(或最简单的)。

目前我想说的是:

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

但我一点都不喜欢,有人愿意吗?

我并不想为此挖掘出正则表达式,对吧?

我知道我的字符串将包含我要搜索的项,所以你可以假设…

当然对于长度为> 1的字符串,

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

当前回答

**计数字符或字符串**

 string st = "asdfasdfasdfsadfasdf/asdfasdfas/dfsdfsdafsdfsd/fsadfasdf/dff";
        int count = 0;
        int location = 0;
       
        while (st.IndexOf("/", location + 1) > 0)
        {
                count++;
                location = st.IndexOf("/", location + 1);
        }
        MessageBox.Show(count.ToString());

其他回答

如果你看看这个网页,有15种不同的方法进行了基准测试,包括使用并行循环。

最快的方法似乎是使用单线程for循环(如果您的。net版本< 4.0)或并行。for循环(如果使用。net > 4.0进行数千次检查)。

假设“ss”是你的搜索字符串,“ch”是你的字符数组(如果你有一个以上的字符你正在寻找),下面是代码的基本要点,有最快的运行时间单线程:

for (int x = 0; x < ss.Length; x++)
{
    for (int y = 0; y < ch.Length; y++)
    {
        for (int a = 0; a < ss[x].Length; a++ )
        {
        if (ss[x][a] == ch[y])
            //it's found. DO what you need to here.
        }
    }
}

还提供了基准测试源代码,以便您可以运行自己的测试。

对于字符串分隔符的情况(而不是字符情况,如主题所述): 字符串源= "@@ once@@@upon@@ a@@@time@@@"; Int count = source。Split(new[] {"@@@"}, StringSplitOptions.RemoveEmptyEntries)。长度- 1; 海报的原始源值("/once/upon/a/time/")自然分隔符是一个字符'/',并且响应确实解释了source. split (char[])选项…

string source = "/once/upon/a/time/";
int count = 0;
foreach (char c in source) 
  if (c == '/') count++;

必须比source.Replace()本身更快。

LINQ适用于所有的集合,因为字符串只是字符的集合,那么下面这个漂亮的小语句怎么样:

var count = source.Count(c => c == '/');

确保你使用了system。linq;在代码文件的顶部,因为. count是来自该名称空间的扩展方法。

str="aaabbbbjjja";
int count = 0;
int size = str.Length;

string[] strarray = new string[size];
for (int i = 0; i < str.Length; i++)
{
    strarray[i] = str.Substring(i, 1);
}
Array.Sort(strarray);
str = "";
for (int i = 0; i < strarray.Length - 1; i++)
{

    if (strarray[i] == strarray[i + 1])
    {

        count++;
    }
    else
    {
        count++;
        str = str + strarray[i] + count;
        count = 0;
    }

}
count++;
str = str + strarray[strarray.Length - 1] + count;

这是用来计算字符出现次数的。本例的输出为"a4b4j3"