How To Remove Duplicate Characters From String In C#

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.

  1. Using LINQ
  2. Using Simple Array
  3. Using HashSet

Below are a few examples of inputs and Outputs.

Example 1

  1. Input: GOOGLE
  2. Result: GOLE

Example 2

  1. Input: MOON
  2. Result: MON

This is an essential technical interview question that may be posed to beginner, intermediate, and experienced candidates.

We previously covered the following.

  1. How to Reverse Number in C#
  2. How to Reverse a String in C#
  3. Palindrome String Program in C#
  4. Palindrome Number in C#
  5. How to Reverse Order of the Given String
  6. 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

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

Execute

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

String Output

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

Up Next
    Ebook Download
    View all
    DateTime in C#
    Read by 1.3k people
    Download Now!
    Learn
    View all