Replacing consecutive duplicate characters with repetition count

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Collections;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            //Replacing consecutive duplicate characters with repetition count

            string str = "aaaaaabbbbbbbbbbeeeddeeffg";

            int counter = 0;

            for (int i = 0; i < str.Length – 1; i++)

            {

                if (str.Substring(i, 1) == str.Substring(i + 1, 1))

                {

                    str = str.Remove(i + 1, 1);

                    counter++;

                    i–;

                }

                else

                {

                    if (counter != 0)

                    {

                        str = str.Insert(i + 1, counter.ToString());

                        counter = 0;

                    }

                }

                if (i + 1 == str.Length – 1 && counter != 0)

                {

                    str = str.Insert(i + 2, counter.ToString());

                    break;

                }

            }

            Console.WriteLine(str);

        }

    }

}

 

a5b9e2d1e1f1g
Press any key to continue . . .

Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s