Reputation: 1
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
Reputation: 2685
Or:
Console.WriteLine(Strings.Replace("I am an alien", " ", "").ToList.Distinct.Count)
Upvotes: 0
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