Saturday, 8 August 2015

How to count repeated characters in an array

using System;

namespace SequenceCount
{
    class Program
    {
        // to count repeated characters in an array
        private void CountRepeatedCharacters()
        {
            string word = "aaabbcccd";
            char[] characters = word.ToCharArray();
            char startingCharacter = characters[0];
            byte count = 1;
            string output = string.Empty;

            for (int i = 1; i < characters.Length; i++)
            {
                if (characters[i] == startingCharacter)
                {
                    count++;
                }

                else
                {
                    output = output + startingCharacter + count.ToString();
                    // set the current character to startingCharacter and set count to 1
                    startingCharacter = characters[i];
                    count = 1;
                }
            }

            output = output + startingCharacter + count.ToString();
            Console.WriteLine("Output will be : " + output);
            Console.ReadLine();
        }

        static void Main(string[] args)
        {
            Program objProgram = new Program();
            objProgram.CountRepeatedCharacters();
        }
    }
}

No comments:

Post a Comment