Aftesmo
Aftesmo

Reputation: 1

How to count unique characters in a string?

For example, for the string "I am a human", the code has to return integer 6 (spaces are not counted).

For space removal, I used:

line = line.Replace(" ", "")

Unfortunately, I'm lost on what to do after.

Upvotes: 0

Views: 287

Answers (2)

G3nt_M3caj
G3nt_M3caj

Reputation: 2685

Or:

Console.WriteLine(Strings.Replace("I am an alien", " ", "").ToList.Distinct.Count)

Upvotes: 0

41686d6564
41686d6564

Reputation: 19641

Since a String is an IEnumerable(Of Char), you may use the Distinct() LINQ method to get the unique characters and then check their Count().

Try something like this:

Dim s As String = "I am a human"
Dim uniqueCharactersCount = s.Where(Function(c) c <> " "c).Distinct().Count()
Console.WriteLine(uniqueCharactersCount)    ' 6

If you're going to be using this a lot, you may convert it to an extension method:

<Runtime.CompilerServices.Extension>
Public Function UniqueCharsCount(s As String, 
                                 Optional excludeSpace As Boolean = True) As Integer
    Dim distinctChars = s.Distinct()
    If excludeSpace Then distinctChars = distinctChars.Where(Function(c) c <> " "c)
    Return distinctChars.Count()
End Function

Usage:

Dim s As String = "I am a human"
Console.WriteLine(s.UniqueCharsCount())    ' 6

Upvotes: 3

Related Questions