提问



我正在做的事情,我意识到我想要计算一个字符串中可以找到多少/,然后它让我感到震惊,有几种方法可以做到,但无法决定什么是最好的(或最简单)是。


目前我正在做类似的事情:


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


但我根本不喜欢它,任何接受者?


我真的不想为此挖出RegEx,是吗?


我知道我的字符串将会有我正在寻找的术语,所以你可以认为......


当然对于字符串,其中 长度> 1


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

最佳参考


如果您使用的是.NET 3.5,则可以使用LINQ在单行中执行此操作:


int count = source.Count(f => f == '/');


如果你不想使用LINQ,你可以使用:


int count = source.Split('/').Length - 1;





您可能会惊讶地发现您的原始技术似乎比其中任何一种快约30%!我刚用/once/on/a/time/做了一个快速的基准测试,结果如下:



  你原来的= 12s

  source.Count=19s

  source.Split=17s

  foreach(来自bobwienholt的回答)= 10s



(时间是50,000,000次迭代,所以你不太可能注意到现实世界中的太多差异。)

其它参考1


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


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

其它参考2


int count = new Regex(Regex.Escape(needle)).Matches(haystack).Count;

其它参考3


如果您希望能够搜索整个字符串,而不仅仅是字符:


src.Select((c, i) => src.Substring(i)).Count(sub => sub.StartsWith(target))


读作对于字符串中的每个字符,将该字符的其余部分从该字符开始作为子字符串;如果它以目标字符串开头,则计算它。

其它参考4


我做了一些研究,发现Richard Watson的解决方案在大多数情况下都是最快的。这是表中包含每个解决方案结果的表(除了那些使用 Regex ,因为它在解析字符串时抛出异常,如test {test)


    Name      | Short/char |  Long/char | Short/short| Long/short |  Long/long |
    Inspite   |         134|        1853|          95|        1146|         671|
    LukeH_1   |         346|        4490|         N/A|         N/A|         N/A|
    LukeH_2   |         152|        1569|         197|        2425|        2171|
Bobwienholt   |         230|        3269|         N/A|         N/A|         N/A|
Richard Watson|          33|         298|         146|         737|         543|
StefanosKargas|         N/A|         N/A|         681|       11884|       12486|


您可以看到,如果在短字符串(10-50个字符)中查找短子串(1-5个字符)的出现次数,则首选原始算法。


此外,对于多字符子字符串,您应该使用以下代码(基于Richard Watson的解决方案)


int count = 0, n = 0;

if(substring != "")
{
    while ((n = source.IndexOf(substring, n, StringComparison.InvariantCulture)) != -1)
    {
        n += substring.Length;
        ++count;
    }
}

其它参考5


LINQ适用于所有集合,因为字符串只是一个字符集合,所以这个漂亮的小单行如何:


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


确保在代码文件的顶部有using System.Linq;,因为.Count是来自该命名空间的扩展方法。

其它参考6


这些都只适用于单字符搜索术语......


countOccurences("the", "the answer is the answer");

int countOccurences(string needle, string haystack)
{
    return (haystack.Length - haystack.Replace(needle,"").Length) / needle.Length;
}


对于更长的针头可能会变得更好......


但必须有一种更优雅的方式。 :)

其它参考7


string source = "/once/upon/a/time/";
int count = 0;
int n = 0;

while ((n = source.IndexOf('/', n)) != -1)
{
   n++;
   count++;
}


在我的计算机上,它比5000万次迭代的每个角色解决方案快约2秒。


2013年修订:


将字符串更改为char [[]]并迭代它。将总时间缩短一两秒,进行50米迭代!


char[] testchars = source.ToCharArray();
foreach (char c in testchars)
{
     if (c == '/')
         count++;
}


这更快:


char[] testchars = source.ToCharArray();
int length = testchars.Length;
for (int n = 0; n < length; n++)
{
    if (testchars[n] == '/')
        count++;
}


为了更好的衡量,从数组末尾迭代到0似乎是最快的,大约5%。


int length = testchars.Length;
for (int n = length-1; n >= 0; n--)
{
    if (testchars[n] == '/')
        count++;
}


我想知道为什么会这样,并且谷歌搜索(我记得反向迭代更快),并发现这个问题,烦人地使用字符串char [[]]技术已经。不过,我认为逆转技巧在这方面是新的。


在C#中迭代字符串中单个字符的最快方法是什么?

其它参考8





source.Split('/').Length-1

其它参考9


Regex.Matches( Regex.Escape(input),  "stringToMatch" ).Count

其它参考10


在C#中,一个不错的String SubString计数器就是这个意想不到的棘手问题:


public static int CCount(String haystack, String needle)
{
    return haystack.Split(new[] { needle }, StringSplitOptions.None).Length - 1;
}

其它参考11


string s = "65 fght 6565 4665 hjk";
int count = 0;
foreach (Match m in Regex.Matches(s, "65"))
  count++;

其它参考12


private int CountWords(string text, string word) {
    int count = (text.Length - text.Replace(word, "").Length) / word.Length;
    return count;
}


因为原始解决方案对于字符来说是最快的,所以我认为它也适用于字符串。所以这是我的贡献。


对于上下文:我在日志文件中寻找失败和成功之类的单词。


GR,


其它参考13


对于任何想要使用String扩展方法的人来说,


这是我使用的基于最好的答案:


public static class StringExtension
{    
    /// <summary> Returns the number of occurences of a string within a string, optional comparison allows case and culture control. </summary>
    public static int Occurrences(this System.String input, string value, StringComparison stringComparisonType = StringComparison.Ordinal)
    {
        if (String.IsNullOrEmpty(value)) return 0;

        int count    = 0;
        int position = 0;

        while ((position = input.IndexOf(value, position, stringComparisonType)) != -1)
        {
            position += value.Length;
            count    += 1;
        }

        return count;
    }

    /// <summary> Returns the number of occurences of a single character within a string. </summary>
    public static int Occurrences(this System.String input, char value)
    {
        int count = 0;
        foreach (char c in input) if (c == value) count += 1;
        return count;
    }
}

其它参考14


我认为最简单的方法是使用正则表达式。这样,您可以获得与使用myVar.Split(x)相同的分割计数,但是在多字符设置中。


string myVar = "do this to count the number of words in my wording so that I can word it up!";
int count = Regex.Split(myVar, "word").Length;

其它参考15


public static int GetNumSubstringOccurrences(string text, string search)
{
    int num = 0;
    int pos = 0;

    if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(search))
    {
        while ((pos = text.IndexOf(search, pos)) > -1)
        {
            num ++;
            pos += search.Length;
        }
    }
    return num;
}

其它参考16


字符串出现的通用函数:


public int getNumberOfOccurencies(String inputString, String checkString)
{
    if (checkString.Length > inputString.Length || checkString.Equals("")) { return 0; }
    int lengthDifference = inputString.Length - checkString.Length;
    int occurencies = 0;
    for (int i = 0; i < lengthDifference; i++) {
        if (inputString.Substring(i, checkString.Length).Equals(checkString)) { occurencies++; i += checkString.Length - 1; } }
    return occurencies;
}

其它参考17


string source = "/once/upon/a/time/";
int count = 0, n = 0;
while ((n = source.IndexOf('/', n) + 1) != 0) count++;


Richard Watson答案的一个变体,提高效率的速度越快,字符串中字符出现的次数越多,代码越少!


虽然我必须说,如果不对每个场景进行广泛测试,我确实看到了一个非常显着的速度改进:


int count = 0;
for (int n = 0; n < source.Length; n++) if (source[n] == '/') count++;

其它参考18


字符串中的字符串


在.. JD JD JD JD等等JDJDJDJDJDJDJDJD等中找到等。


var strOrigin = " .. JD JD JD JD etc. and etc. JDJDJDJDJDJDJDJD and etc.";
var searchStr = "etc";
int count = (strOrigin.Length - strOrigin.Replace(searchStr, "").Length)/searchStr.Length.


检查性能,然后将其丢弃为不健全/笨拙...

其它参考19


string Name = "Very good nice one is very good but is very good nice one this is called the term";
bool valid=true;
int count = 0;
int k=0;
int m = 0;
while (valid)
{
    k = Name.Substring(m,Name.Length-m).IndexOf("good");
    if (k != -1)
    {
        count++;
        m = m + k + 4;
    }
    else
        valid = false;
}
Console.WriteLine(count + " Times accures");

其它参考20


            var conditionalStatement = conditionSetting.Value;

            //order of replace matters, remove == before =, incase of ===
            conditionalStatement = conditionalStatement.Replace("==", "~").Replace("!=", "~").Replace('=', '~').Replace('!', '~').Replace('>', '~').Replace('<', '~').Replace(">=", "~").Replace("<=", "~");

            var listOfValidConditions = new List<string>() { "!=", "==", ">", "<", ">=", "<=" };

            if (conditionalStatement.Count(x => x == '~') != 1)
            {
                result.InvalidFieldList.Add(new KeyFieldData(batch.DECurrentField, "The IsDoubleKeyCondition does not contain a supported conditional statement. Contact System Administrator."));
                result.Status = ValidatorStatus.Fail;
                return result;
            }


需要执行类似于从字符串测试条件语句的操作。


用单个字符替换了我正在寻找的东西并计算单个字符的实例。


显然,在发生这种情况之前,需要检查您使用的单个字符是否存在于字符串中以避免错误计数。

其它参考21


string s = "HOWLYH THIS ACTUALLY WORKSH WOWH";
int count = 0;
for (int i = 0; i < s.Length; i++)
   if (s[i] == 'H') count++;


它只检查字符串中的每个字符,如果字符是您要搜索的字符,则添加一个来计数。

其它参考22


如果您查看此网页,则会对15种不同的方法进行基准测试,包括使用并行循环。[47]


最快的方法似乎是使用单线程for循环(如果你有.Net版本< 4.0)或parallel.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.
        }
    }
}


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

其它参考23


以为我会将我的扩展方法抛入环中(有关详细信息,请参阅注释)。我没有做任何正式的替补标记,但我认为对于大多数情况来说它必须非常快。


编辑:好的 - 所以这个问题让我想知道我们当前实现的性能如何与这里提出的一些解决方案相叠加。我决定做一个小板凳标记,发现我们的解决方案非常符合Richard Watson提供的解决方案的性能,直到您使用大字符串(100 Kb +),大型子串(32 Kb +)进行积极搜索)和许多嵌入式重复(10K +)。那时我们的解决方案速度慢了2到4倍。鉴于此以及我们非常喜欢Richard Watson提出的解决方案这一事实,我们已相应地重构了我们的解决方案。我只想让任何可能从中受益的人都可以使用它。


原始解决方案:


    /// <summary>
    /// Counts the number of occurrences of the specified substring within
    /// the current string.
    /// </summary>
    /// <param name="s">The current string.</param>
    /// <param name="substring">The substring we are searching for.</param>
    /// <param name="aggressiveSearch">Indicates whether or not the algorithm 
    /// should be aggressive in its search behavior (see Remarks). Default 
    /// behavior is non-aggressive.</param>
    /// <remarks>This algorithm has two search modes - aggressive and 
    /// non-aggressive. When in aggressive search mode (aggressiveSearch = 
    /// true), the algorithm will try to match at every possible starting 
    /// character index within the string. When false, all subsequent 
    /// character indexes within a substring match will not be evaluated. 
    /// For example, if the string was 'abbbc' and we were searching for 
    /// the substring 'bb', then aggressive search would find 2 matches 
    /// with starting indexes of 1 and 2. Non aggressive search would find 
    /// just 1 match with starting index at 1. After the match was made, 
    /// the non aggressive search would attempt to make it's next match 
    /// starting at index 3 instead of 2.</remarks>
    /// <returns>The count of occurrences of the substring within the string.</returns>
    public static int CountOccurrences(this string s, string substring, 
        bool aggressiveSearch = false)
    {
        // if s or substring is null or empty, substring cannot be found in s
        if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(substring))
            return 0;

        // if the length of substring is greater than the length of s,
        // substring cannot be found in s
        if (substring.Length > s.Length)
            return 0;

        var sChars = s.ToCharArray();
        var substringChars = substring.ToCharArray();
        var count = 0;
        var sCharsIndex = 0;

        // substring cannot start in s beyond following index
        var lastStartIndex = sChars.Length - substringChars.Length;

        while (sCharsIndex <= lastStartIndex)
        {
            if (sChars[sCharsIndex] == substringChars[0])
            {
                // potential match checking
                var match = true;
                var offset = 1;
                while (offset < substringChars.Length)
                {
                    if (sChars[sCharsIndex + offset] != substringChars[offset])
                    {
                        match = false;
                        break;
                    }
                    offset++;
                }
                if (match)
                {
                    count++;
                    // if aggressive, just advance to next char in s, otherwise, 
                    // skip past the match just found in s
                    sCharsIndex += aggressiveSearch ? 1 : substringChars.Length;
                }
                else
                {
                    // no match found, just move to next char in s
                    sCharsIndex++;
                }
            }
            else
            {
                // no match at current index, move along
                sCharsIndex++;
            }
        }

        return count;
    }


这是我们修订的解决方案:


    /// <summary>
    /// Counts the number of occurrences of the specified substring within
    /// the current string.
    /// </summary>
    /// <param name="s">The current string.</param>
    /// <param name="substring">The substring we are searching for.</param>
    /// <param name="aggressiveSearch">Indicates whether or not the algorithm 
    /// should be aggressive in its search behavior (see Remarks). Default 
    /// behavior is non-aggressive.</param>
    /// <remarks>This algorithm has two search modes - aggressive and 
    /// non-aggressive. When in aggressive search mode (aggressiveSearch = 
    /// true), the algorithm will try to match at every possible starting 
    /// character index within the string. When false, all subsequent 
    /// character indexes within a substring match will not be evaluated. 
    /// For example, if the string was 'abbbc' and we were searching for 
    /// the substring 'bb', then aggressive search would find 2 matches 
    /// with starting indexes of 1 and 2. Non aggressive search would find 
    /// just 1 match with starting index at 1. After the match was made, 
    /// the non aggressive search would attempt to make it's next match 
    /// starting at index 3 instead of 2.</remarks>
    /// <returns>The count of occurrences of the substring within the string.</returns>
    public static int CountOccurrences(this string s, string substring, 
        bool aggressiveSearch = false)
    {
        // if s or substring is null or empty, substring cannot be found in s
        if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(substring))
            return 0;

        // if the length of substring is greater than the length of s,
        // substring cannot be found in s
        if (substring.Length > s.Length)
            return 0;

        int count = 0, n = 0;
        while ((n = s.IndexOf(substring, n, StringComparison.InvariantCulture)) != -1)
        {
            if (aggressiveSearch)
                n++;
            else
                n += substring.Length;
            count++;
        }

        return count;
    }

其它参考24


我最初的看法给了我类似的东西:


public static int CountOccurrences(string original, string substring)
{
    if (string.IsNullOrEmpty(substring))
        return 0;
    if (substring.Length == 1)
        return CountOccurrences(original, substring[0]);
    if (string.IsNullOrEmpty(original) ||
        substring.Length > original.Length)
        return 0;
    int substringCount = 0;
    for (int charIndex = 0; charIndex < original.Length; charIndex++)
    {
        for (int subCharIndex = 0, secondaryCharIndex = charIndex; subCharIndex < substring.Length && secondaryCharIndex < original.Length; subCharIndex++, secondaryCharIndex++)
        {
            if (substring[subCharIndex] != original[secondaryCharIndex])
                goto continueOuter;
        }
        if (charIndex + substring.Length > original.Length)
            break;
        charIndex += substring.Length - 1;
        substringCount++;
    continueOuter:
        ;
    }
    return substringCount;
}

public static int CountOccurrences(string original, char @char)
{
    if (string.IsNullOrEmpty(original))
        return 0;
    int substringCount = 0;
    for (int charIndex = 0; charIndex < original.Length; charIndex++)
        if (@char == original[charIndex])
            substringCount++;
    return substringCount;
}


使用替换和分割的干草堆方法中的针产生21秒以上,而这需要大约15.2秒。


在添加一个将substring.Length - 1添加到charIndex(就像它应该)的位之后编辑,它是在11.6秒。


编辑2:我使用了一个包含26个双字符字符串的字符串,以下是更新为相同示例文本的时间:


大海捞针(OP版):7.8秒


建议机制:4.6秒。


编辑3:添加单个字符的角落情况,它变为1.2秒。


编辑4:对于上下文:使用了5000万次迭代。

其它参考25


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

其它参考26


string search = "/string";
var occurrences = (regex.Match(search, @"\/")).Count;


每当程序完全找到/s(区分大小写)时,这将计算
它的出现次数将存储在变量eventss中

其它参考27


对于字符串分隔符的情况(不是对于char情况,如主题所说):

string source =@@@ once @@@ on @@@ a @@@ time @@@;

int count=source.Split(new [[]] {@@@},StringSplitOptions.RemoveEmptyEntries).Length - 1;



海报的原始源值(/once/on/a/time/)自然分隔符是一个字符/,响应确实解释了source.Split(char [[]])选项虽然...