Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count unique characters in string [duplicate]

Tags:

string

c#

char

Lets say we have variable myString="blabla" or mystring=998769

myString.Length; //will get you your result

myString.Count(char.IsLetter);    //if you only want the count of letters:

How to get, unique character count? I mean for "blabla" result must be 3, doe "998769" it will be 4. Is there ready to go function? any suggestions?

like image 310
heron Avatar asked Nov 28 '22 07:11

heron


1 Answers

You can use LINQ:

var count = myString.Distinct().Count();

It uses a fact, that string implements IEnumerable<char>.

Without LINQ, you can do the same stuff Distinct does internally and use HashSet<char>:

var count = (new HashSet<char>(myString)).Count;
like image 122
MarcinJuraszek Avatar answered Dec 05 '22 01:12

MarcinJuraszek