Introduction
In this article, we will examine different methods for eliminating duplicate characters from the specified string in C#.
There are numerous methods to erase duplicate characters from the string, but I will demonstrate three methods for doing so below.
- Using LINQ
- Using Simple Array
- Using HashSet
Below are a few examples of inputs and Outputs.
Example 1
- Input: GOOGLE
- Result: GOLE
Example 2
- Input: MOON
- Result: MON
This is an essential technical interview question that may be posed to beginner, intermediate, and experienced candidates.
We previously covered the following.
- How to Reverse Number in C#
- How to Reverse a String in C#
- Palindrome String Program in C#
- Palindrome Number in C#
- How to Reverse Order of the Given String
- How To Reverse Each Word Of Given String
Let’s start.
Using LINQ
Console.WriteLine("Enter a String");
var str = Console.ReadLine();
var strArray = str.ToCharArray()
.Distinct()
.ToArray();
string result = new string(strArray);
Console.WriteLine($"{result}");
Console.ReadLine();
Output

Using HashSet
We are going to implement the same functionality using HashSet.
Console.WriteLine("Enter a String");
var str = Console.ReadLine();
var strInput = new HashSet<char>(str);
string result = new string(strInput.ToArray());
Console.WriteLine($"{result}");
Console.ReadLine();
Let's execute and see the output.
Output

Now we will try another simple array method to implement.
Using the Simple Array Method
Console.WriteLine("Enter a String");
var str = Console.ReadLine();
string result = string.Empty;
for (int i = 0; i < str.Length; i++)
{
if (!result.Contains(str[i]))
{
result += str[i];
}
}
Console.WriteLine($"{result}");
Console.ReadLine();
Output

We have learned three distinct methods to eliminate duplicate characters from the string. We hope you find this article enjoyable and useful.

Join the conversation! Your thoughts help the community grow.