How to count unique characters in string [duplicat

2019-01-09 18:02发布

This question already has an answer here:

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?

标签: c# string char
3条回答
闹够了就滚
2楼-- · 2019-01-09 18:31

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;
查看更多
我命由我不由天
3楼-- · 2019-01-09 18:42

If you handle only ANSI text in English (or characters from BMP) then 80% times if you write:

myString.Distinct().Count()

You will live happy and won't ever have any trouble. Let me post this answer only for who will really need to handle that in the proper way. I'd say everyone should but I know it's not true (quote from Wikipedia):

Because the most commonly used characters are all in the Basic Multilingual Plane, handling of surrogate pairs is often not thoroughly tested. This leads to persistent bugs and potential security holes, even in popular and well-reviewed application software (e.g. CVE-2008-2938, CVE-2012-2135)

Problem of our first naïve solution is that it doesn't handle Unicode properly and it also doesn't consider what user perceive as character. Let's try "

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-09 18:43

If you're using C# then Linq comes nicely to the rescue - again:

"blabla".Distinct().Count()

will do it.

查看更多
登录 后发表回答