Find the first nonrepeated character in a word

using System;
using System.Collections.Generic;
using System.Text;
namespace Mono
{
    class Mono
    {
        static void Main(string[] args)
        {
            try
            {
                //Code to find the first nonrepeated character in a word
                Console.Write("Enter a word to test: ");
                string str = Console.ReadLine();
                int flag = 0;
                for (int i = 0; i < str.Length; i++)
                {
                    flag = 0;
                    for (int j = i + 1; j < str.Length; j++)
                    {
                        if (str[i] == str[j])
                        {
                            str = str.Remove(j, 1);
                            j–;
                            flag = 1;
                        }
                    }
                    if (flag == 0)
                    {
                        Console.WriteLine("First non repetitive character is " + str[i]);
                        break;
                    }
                }
                if (flag == 1)
                {
                    Console.WriteLine("All characters are repetitive.");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message.ToString());
            }
        }
    }
}
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