How to remove all duplicate characters from a string in C#

2 Answers

0 votes
using System;
using System.Linq;

class Program
{
    static string remove_duplicate_characters(string s) {
        return new string(s.ToCharArray().Distinct().ToArray());
    }
    static void Main() {
        string s = "c#### ppprooooooogramminggg";

        s = remove_duplicate_characters(s);
        
        Console.Write(s);
    }
}
  
  
  
/*
run:
  
c# progamin
  
*/

 



answered Oct 29, 2019 by avibootz
0 votes
using System;
using System.Collections.Generic;

class Program
{
    static string remove_duplicate_characters(string s) {
        var hs = new HashSet<char>(s);
        
        return string.Join("", hs);
    }
    static void Main() {
        string s = "c#### ppprooooooogramminggg";

        s = remove_duplicate_characters(s);
        
        Console.Write(s);
    }
}
  
  
  
/*
run:
  
c# progamin
  
*/

 



answered Oct 29, 2019 by avibootz
...