C# Program To Find Duplicate Characters In a String
Code Snippet How To C#

C# Program To Find Duplicate Characters In a String

Mishel Shaji
Mishel Shaji

In this post, we'll learn three different ways to find duplicate characters in a string using C#.

Please import the following namespaces first before continuing.

using System.Linq;
using System.Collections.Generic;

1) Using LINQ GroupBy

This is one of the easiest ways to find duplicate characters from a string. In this example, first, we use the GroupBy() method from the System.Linq namespace to group the characters.

Then we filter the groups with more than one member using the LINQ Where() method to find duplicate characters.

The key of each group is the character based on which the group is formed.

string s = "This is a string";
var groups = s.GroupBy(c => c).Where(g=>g.Count() > 1);
foreach (var group in groups)
{
    Console.WriteLine(group.Key);
}

Using IndexOf Method

In this example, we're comparing the index of each character of the string.

First, we use a foreach loop to fetch each character from the string, Then we find the first and last index of the character. If the first and last index of the character is the same, the character occurs only once. Else, the character occurs multiple times in the string.

string s = "This is a string";
var duplicates = new List<char>();
foreach (var item in s)
{
    if (s.IndexOf(item) != s.LastIndexOf(item) && 
        !duplicates.Contains(item))
    {
        duplicates.Add(item);
    }
}

Console.WriteLine(string.Join(",", duplicates));

Using for Loop To Compare

This is the most basic way to solve this problem. In this method, we have to use two foreach loops.

In this example, we take each character from the string and compare it with all other characters in the string. If a match is found, the count is incremented. If the total count of a character is more than 1, it means that the character occurred multiple times in the string.

string s = "This is a string";
var duplicates = new List<char>();
foreach (var item in s)
{
    int charCount = 0;
    foreach (var chars in s)
    {
        if (item == chars) 
        {
            charCount++;
        }
    }

    if(charCount > 1 && !duplicates.Contains(item))
    {
        duplicates.Add(item);
    }
}
Console.WriteLine(string.Join(",", duplicates));

If you have any suggestions or a better solution, please share them in the comments.