In this post, here is the c# code to count the occurrences of a particular character in a given string.
Suppose there is a case  where we may want to check whether the string contains particular character or not.
And we may want to count the occurrences of the character, in that case you can use this method and if count =0, then it means the character is not found.
Below are the 2 methods for the same logic, you can use whatever you want.

Method 1 :

        /// <summary>
        /// Method to count the occurrences of a charcter in a string
        /// </summary>
        /// <param name=”inputString”>InputString</param>
        /// <param name=”SearchChar”>character to count</param>
        /// <param name=”matchCase”>True-MatchCase,False-IgnoreCase</param>
        /// <returns>count of given character</returns>
        /// <remarks></remarks>
        public int CharCountInString(string inputString, char SearchChar, bool matchCase)
        {
            int count = 0;
            char[] chrArr;
            if (matchCase)
            {
                chrArr = inputString.ToCharArray();
            }
            else
            {
                chrArr = inputString.ToLower().ToCharArray();
                SearchChar = char.ToLower(SearchChar);
            }
            foreach (char ch in chrArr)
            {
                if (ch == SearchChar)
                {
                    count++;
                }
            }
            return count;
        }

Method 2 :

 
        /// <summary>
        /// Method to count the occurrences of a charcter in a string using LINQ
        /// </summary>
        /// <param name=”inputString”>InputString</param>
        /// <param name=”SearchChar”>character to count</param>
        /// <param name=”matchCase”>True-MatchCase,False-IgnoreCase</param>
        /// <returns>count of given character</returns>
        /// <remarks>.Net > 3.5 Version </remarks>
        public int CharCountInStringUsingLinq(string inputString, char SearchChar, bool matchCase)
        {
            int count = 0;
            if (matchCase)
            {
                count = inputString.Count(x => x == SearchChar);
            }
            else
            {
                inputString = inputString.ToLower();
                SearchChar = char.ToLower(SearchChar);
                count = inputString.Count(x => x == SearchChar);
            }
            return count;
        }

Leave a Reply

Your email address will not be published. Required fields are marked *