Counting how many times a certain char appears in a string before any other char appears

前端 未结 12 818
再見小時候
再見小時候 2021-01-03 17:17

I have many strings. Each string is prepended with at least 1 $. What is the best way to loop through the chars of each string to count how many $\

相关标签:
12条回答
  • 2021-01-03 17:59
    int count = myString.TakeWhile(c => c == '$').Count();
    

    And without LINQ

    int count = 0;
    while(count < myString.Length && myString[count] == '$') count++;
    
    0 讨论(0)
  • 2021-01-03 18:00

    just a simple answer:

        public static int CountChars(string myString, char myChar)
        {
            int count = 0;
            for (int i = 0; i < myString.Length; i++)
            {
                if (myString[i] == myChar) ++count;
            }
            return count;
        }
    

    Cheers! - Rick

    0 讨论(0)
  • 2021-01-03 18:01

    The simplest approach would be to use LINQ:

    var count = text.TakeWhile(c => c == '$').Count();
    

    There are certainly more efficient approaches, but that's probably the simplest.

    0 讨论(0)
  • 2021-01-03 18:02

    You could do this, it doesn't require LINQ, but it's not the best way to do it(since you make split the whole string and put it in an array and just pick the length of it, you could better just do a while loop and check every character), but it works.

    int count = test.Split('$').Length - 1;
    
    0 讨论(0)
  • 2021-01-03 18:02

    One approach you could take is the following method:

    // Counts how many of a certain character occurs in the given string
    public static int CharCountInString(char chr, string str)
    {
        return str.Split(chr).Length-1;
    }
    

    As per the parameters this method returns the count of a specific character within a specific string.

    This method works by splitting the string into an array by the specified character and then returning the length of that array -1.

    0 讨论(0)
  • 2021-01-03 18:03
    int count = yourText.Length - yourText.TrimStart('$').Length;
    
    0 讨论(0)
提交回复
热议问题