Thursday, September 13, 2018

How would you count occurrences of a char within a string?


In many interviews, i faces a problem with the getting count of occurrences of a char within a string. Mostly i ignored these question and i replied like "Sorry, I don't know &  Sorry, i cannot reply".

Finally, i mind it and write a simple code as below :


using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CharOccuranceInString
{
    class Program
    {
        static void Main(string[] args)
        {
            #region Occurance of char in a string using c#
            
            string source = "abcaadbcdbbcd";
            int countA = 0;
            int countB = 0;
            int countC = 0;
            int countD = 0;
            foreach (char c in source)
            {
                if (c == 'a') countA++;
                if (c == 'b') countB++;
                if (c == 'c') countC++;
                if (c == 'd') countD++;
            }

            Console.WriteLine("Occurance of a=" + countA.ToString() +
                                   "\n Occurance of b=" + countB.ToString() +
                                   "\n Occurance of c=" + countC.ToString() +
                                   "\n Occurance of d=" + countD.ToString());

            Console.ReadKey();
            #endregion

        }
    }
}