0

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
1
  • Looks more like homework ;0) Commented Jan 23, 2016 at 17:09

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much! I just had to fix up a bit of your code cause it didn't originally work
I had to make it Textbox1.Text.Length - 1
1

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

4 Comments

I don't see SubString anywhere here.
This method doesn't need substring that's why you can't see it
The question states to specfically use SubString
Yeah I can see that.IMO nothing hurt to post an answer that solves a question..If you don't want to take this as answer let it be, future visitors might found this useful
0

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

1 Comment

This is just an example that shows how to use Substring. It should count all upper-case letters "A".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.