Remove all duplicates from a given string in C#

ProgrammingServer Side ProgrammingCsharp

Here is the string.

string str = "ppqqrr";

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

var res = new HashSet<char>(str);

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 str = "ppqqrr";
         Console.WriteLine("Initial String: "+str);
         var res = new HashSet<char>(str);
         Console.Write("New String after removing duplicates:");
         foreach (char c in res){
            Console.Write(c);
         }  
      }
   }
}

Output

Initial String: ppqqrr
New String after removing duplicates:pqr
raja
Published on 11-Sep-2018 12:51:23
Advertisements