Reputation: 93
I'm teaching myself VB.net and I'm trying to complete challenges.
I'm stuck on this challenge.
I'm trying to figure out how to go about counting specific characters in a string using SubString.
I should not use string processing functions other than: Trim, ToUpper, ToLower, Indexof, SubString.
Add one button for each vowel of the alphabet. When clicked, the output is the count of that vowel in the text entered.Using SubString, the code under the button click event handler,displays how many times the corresponding character appears in the text.
This is what I have so far, but how should I incorporate SubString
?
Dim counter As Integer = 0
For Each vowelA As Char In TextBox1.Text
If vowelA = "a" Then
counter += 1
End If
If vowelA = "A" Then
counter += 1
End If
Next
Upvotes: 0
Views: 612
Reputation: 21885
Without using a substring()
function,
Function count_vowels(ByVal str As String, ByVal chr As String) As Integer
str = str.ToUpper()
chr = chr.ToUpper()
count_vowels = str.Split(chr).Length - 1
Return count_vowels
End Function
Usage:
Dim counter As Integer = 0
counter = count_vowels(TextBox3.Text, "a")
or simply use
counter = TextBox1.Text.ToUpper.Split("a".ToUpper).Length - 1
Upvotes: 1
Reputation: 1985
Here I incorporated also .ToUpper so you don't need to compare "a" and "A"
Dim counter As Integer = 0
For i = 0 To TextBox1.Text.Length - 1
If TextBox1.Text.ToUpper.Substring(i, 1) = "A" Then
counter += 1
End If
Next
Upvotes: 2
Reputation: 4036
Try something like this:
Dim pos As Integer = 0
Dim letter as String
While pos < TextBox1.Text.Length
letter = TextBox1.Text.Substring(pos, 1)
If letter = "A" Then
counter += 1
End If
pos += 1
End While
Upvotes: 0