Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get distinct characters?

Tags:

c#

I have a code like

string code = "AABBDDCCRRFF"; 

In this code, I want to retrieve only distinct characters

The Output should be like:

ANS: ABDCRF 
like image 684
Domnic Avatar asked Feb 28 '11 12:02

Domnic


People also ask

What are the distinct characters?

It means different characters. For example : 'a' and 'b' are distinct while 'a' and 'a' are same. So, a string say, “absgj” contains 5 distinct characters. Also string, “hello” contains only 4 distinct characters.

How do I get unique values from a string?

A unique string consists of characters that occur only once. To check for uniqueness, compare each character with the rest of the string. If a character is repeated, then the string is not unique.

How do I find a unique character in a string 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.


2 Answers

string code = "AABBDDCCRRFF"; string answer = new String(code.Distinct().ToArray()); 
like image 135
Robin Day Avatar answered Oct 02 '22 03:10

Robin Day


Linq's Distinct returns distinct elements from a sequence. As the String class implements IEnumerable<char>, Distinct in this context returns an IEnumerable<char> containing all of the unique characters in the string.

code.Distinct(); 
like image 30
Geoff Appleford Avatar answered Oct 02 '22 04:10

Geoff Appleford