Saturday, June 10, 2017

C# - Find each character occurance count in a string C#

In this article, we will find each character count in a given string in C#

class Program
    {
        static void Main(string[] args)
        {
            #region Find Each Char Count in a string

            Console.WriteLine("Please enter string");
            string input = Convert.ToString(Console.ReadLine());
            Dictionary objdict = GetAllCharOccurenceCount(input);
            foreach (var temp in objdict)
            {
                Console.WriteLine("Key: {0}, Value: {1}", temp.Key, temp.Value);
            }
            Console.ReadLine();

            #endregion
        }

      #region Find Each Char Count in a string
       ///

        /// This method will return a dictonary of string and int
        ///
        /// input string
        /// dictonary of string, int
        private static Dictionary GetAllCharOccurenceCount(string input)
        {
            Dictionary objdict = new Dictionary();
            foreach (char c in input)
            {
                if (objdict.ContainsKey(c.ToString()))
                {
                    objdict[c.ToString()] = objdict[c.ToString()] + 1; // this will increase the count of                                                                                                                // particular character in the dictionary
                }
                else
                {
                    objdict.Add(c.ToString(), 1); // first add the character and count as 1 in the dictionary;
                                                                   // if the character is found again, it will go to IF condition
                }
            }
            return objdict;
        }

        #endregion

}

CONSOLE OUTPUT:

Please enter string
NARENDRA DAMODARDAS MODI
Key: N, Value: 2
Key: A, Value: 5
Key: R, Value: 3
Key: E, Value: 1
Key: D, Value: 5
Key:  , Value: 2
Key: M, Value: 2
Key: O, Value: 2
Key: S, Value: 1
Key: I, Value: 1



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 (...