Tuesday, 17 May 2022

C# code to remove duplicate character in a string

Most common or you can say frequently asked questions in .Net interviews for Beginner to intermediate. There are several ways in .Net using C# through which you can remove or find duplicate characters in a string. 

Lets see one bye one. Suppose we have input string as : India then output should be Inda 

Method 1: Using C# HashSet . 

.Net have many inbuilt data structures with multiple functionalities. HashSet is one of the generic collection data structure which holds unique values only. If you provide the duplicates then it omits the duplicate values and keep only unique values without any exception. 

Issue with this method is like it treats Caps and small case chars different. So either you have to make all characters to upper case or lower case

See below example

 

Method 2: Using C# Linq's Distinct method on array . 

Linq have many methods through which we can manipulate Collections. So there is inbuilt function which gets distinct items from a collection. Let's see it with example:

Method 3: Using Loop and string's inbuilt methods . 

String type have inbuilt method thorugh which you can check if the string have a character or not using the IndexOf method. This method returns interger or the position of the character in the string. If it's negative means character does'nt exists and if it is greater or equal to 0 then that character exists in that string.
String is actually array of characters. You can either change it to array of character by using method .TocharArray() or can directly treat it as char array. Let's see below example

There are several ways to find this. You can explore and let us know which method you find better and how you did it.
Happy Coding

0 comments:

Post a Comment