C# Program to remove duplicate characters from String

ProgrammingServer Side ProgrammingCsharp

Use Hashset to remove duplicate characters.

Here is the string −

string myStr = "kkllmmnnoo";

Now, use HashSet to map the string to char. This will remove the duplicate characters from a string.

var unique = new HashSet<char>(myStr);

Let us see the complete example −

Example

 Live Demo

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

namespace Demo {
   class Program {
      static void Main(string[] args) {
         string myStr = "kkllmmnnoo";
         Console.WriteLine("Initial String: "+myStr);
         var unique = new HashSet<char>(myStr);
         Console.Write("New String after removing duplicates: ");
         foreach (char c in unique)
         Console.Write(c);
      }
   }
}

Output

Initial String: kkllmmnnoo
New String after removing duplicates: klmno
raja
Published on 11-Sep-2018 08:09:55
Advertisements