Saturday, June 10, 2017

C# - Find a given character count in a string

In this article, we will find the count of a particular character in a given string using c#

class Program
    {
        static void Main(string[] args)
        {
            #region Find a given character count in a string

            Console.WriteLine("Enter a String :");
            string str = Console.ReadLine();
            Console.WriteLine("Enter the character:");
            char ch = Console.ReadLine();
            Console.WriteLine("The character " + ch + " occurs " + GetCharacterCount(str, ch) + " times in the given string");
            Console.ReadKey();

            #endregion
           
          }

        #region Find a given character count in a string

        private static int GetCharacterCount(string str, char ch)
        {
            int count = 0;
            int i = 0;

            // Search starts in the string from index (where the given character first occurs in the string at                // start index 0) and loops through entire string till the index not equals to -1
            while ((i = str.IndexOf(ch, i)) != -1)
            {
                i += ch.ToString().Length; // keep increasing the loop count
                count++;
            }
            return count;

        }

        #endregion
}

Console Output:

Enter a String :
AMRENDRA BAHUBALI
Enter the character:
A
The character A occurs 4 times in the given string

No comments:

Post a Comment

SQL INTERVIEW QUESTIONS (SCENARIO BASED) - Part 1

FINDING Second Highest Salary in SQL CREATE TABLE #EMP ( NAME NVARCHAR ( 100 ), SALARY BIGINT ) INSERT INTO #EMP VALUES (...