Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To fetch the unique characters from a string?

Tags:

string

c#

I want to extract unique characters from a string. For example:- 'AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ' will return 'ABCFGDJ'

I have tried below piece of code but now I want to optimize it. Please suggest if anyone knows.

static string extract(string original)
 {
        List<char> characters = new List<char>();   
        string unique = string.Empty; 
        foreach (char letter in original.ToCharArray())    
         {  
             if (!characters.Contains(letter))   
             {      
                  characters.Add(letter);   
              }            
          }  
        foreach (char letter in characters)
        {  
              unique += letter;    
         }     
     return unique;
 } 
like image 633
Rahul Tripathi Avatar asked Sep 12 '12 12:09

Rahul Tripathi


People also ask

How do I find unique characters in a string in C++?

First we will initialize all values of counter array to 0 and all values of index array to n (length of string). On traversal of the string str and for every character c, increase count[x], if count[x] = 1, index[x] = i. If count[x] = 2, index[x] = n. Sort indexes and print characters.

How do I find unique characters in a text file in Python?

fh = open('my. txt','r'). read() unique_chars = set(fh) len(unique_chars) #for the length.


5 Answers

I don't know if this is faster, but surely shorter

string s = "AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ";
var newstr = String.Join("", s.Distinct());
like image 50
L.B Avatar answered Oct 13 '22 07:10

L.B


Another LINQ approach, but not using string.Join:

var result = new string(original.Distinct().ToArray());

I honestly don't know which approach to string creation would be faster. It probably depends on whether string.Join ends up internally converting each element to a string before appending to a StringBuilder, or whether it has custom support for some well-known types to avoid that.

like image 21
Jon Skeet Avatar answered Oct 13 '22 07:10

Jon Skeet


How about

var result = string.Join("", "AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ".Distinct());

Make sure that you include System.Linq namespace.

like image 35
Nikhil Agrawal Avatar answered Oct 13 '22 06:10

Nikhil Agrawal


Try this

string str = "AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ"; 
string answer = new String(str.Distinct().ToArray()); 

I hope this helps.

like image 34
MoonKnight Avatar answered Oct 13 '22 06:10

MoonKnight


if "AAABBBAAA" should return "ABA", then the following does it. Albeit not very fast.

List<char> no_repeats = new List<char>();
no_repeats.Add(s[0]);
for (int i = 1; i < s.Length; i++)
{
    if (s[i] != no_repeats.Last()) no_repeats.Add(s[i]);
}
string result = string.Join("", no_repeats);
like image 28
zeFrenchy Avatar answered Oct 13 '22 06:10

zeFrenchy