Find duplicate characters in string

Our task is simple, find all the duplicate characters in a string.

Input: I am test program

Output: a m t r

Algorithm: Logic is quite simple, see below steps:

  1. Check for input string validity.
    1. If string is not valid prompt user.
  2. Create a dictionary that has character as KEY and, their count as VALUE.
  3. Loop over the input string,
    1. If current character is already exists in dictionary then increment its count by 1.
    2. If current character doesn’t exist in dictionary than add it to the dictionary and set 1 as it’s count because we have found it once.
  4. Loop over the dictionary and check for value, if you find any item whose value is higher than 1 then print it.
  5. If there is no item whose value is not higher than 1 then prompt user.

Code in C#:

void PrintDuplicateCharacters(string strInput)
{
    if (string.IsNullOrWhiteSpace(strInput))
    {
        Console.WriteLine("Input is not valid");
    }
    else
    {
        var dict = new Dictionary<charint>();
        foreach (var item in strInput)
        {
            if (Equals(item, ' '))
            {
                continue;
            }
 
            if (dict.ContainsKey(item))
            {
                dict[item]++;
            }
            else
            {
                dict.Add(item, 1);
            }
        }
 
        bool isAnyCharacterFound = false;
        foreach (var item in dict)
        {
            if (item.Value > 1)
            {
                Console.WriteLine(item.Key);
                isAnyCharacterFound = true;
            }
        }
 
        if (!isAnyCharacterFound)
        {
            Console.WriteLine("No duplicate character found");
        }
    }
    Console.ReadKey();
}
Advertisements

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