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
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.
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.
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.
string code = "AABBDDCCRRFF"; string answer = new String(code.Distinct().ToArray());
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With