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

前端 未结 12 923
再見小時候
再見小時候 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 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.

提交回复
热议问题