Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you remove duplicate characters in a string?

Tags:

c#

I have to implements a function that takes a string as an input and finds the non-duplicate character from this string.

So an an example is if I pass string str = "DHCD" it will return "DHC" or str2 = "KLKLHHMO" it will return "KLHMO"

like image 522
Red Hot Avatar asked Feb 26 '09 01:02

Red Hot


People also ask

How do I find duplicate characters in a string?

To find the duplicate character from the string, we count the occurrence of each character in the string. If count is greater than 1, it implies that a character has a duplicate entry in the string. In above example, the characters highlighted in green are duplicate characters.


1 Answers

A Linq approach:

public static string RemoveDuplicates(string input)
{
    return new string(input.ToCharArray().Distinct().ToArray());
}
like image 94
Christian C. Salvadó Avatar answered Oct 25 '22 18:10

Christian C. Salvadó