I'm busy working on past exam papers in preparation for a Visual Basic exam. I need help with the following question which I'm stuck with.
Write a function procedure to calculate the number of times the characters "e", "f" and "g" appears in a string
I tried to write the psuedo code and came up with the following.
Loop through each individual character in the string
If the character = "e","f" or "g" add 1 to number of characters
Exit loop
Display total in messagebox
How do I loop through individual characters in a string (using a for
loop) and how do I count the number of times a specific character appears in a string?
Visual Basic loop structures allow you to run one or more lines of code repetitively. You can repeat the statements in a loop structure until a condition is True , until a condition is False , a specified number of times, or once for each element in a collection.
In VB.NET, string is a sequential collection of characters that is called a text. The String keyword is used to create a string variable that stores the text value. The name of the string class is System.
Counter variable gets an incremental value for each character, from 1 to the length of the string variable (i.e. Len(mystring)). On every step of the For-Next Loop, a character in mystring will be caught by the Mid function. Mid works in same way as the MID formula, it returns a string part from a source parameter.
The answer greatly depends on what you’ve already learned in your course work and which functions you are supposed to use.
But in general, looping over the characters in a string is as easy as this:
Dim s As String = "test"
For Each c As Char in s
' Count c
Next
As for counting, simply have separate counter variables (eCount As Integer
etc.) for each character and increment them when c
equals that character – obviously that approach doesn’t scale well once you increase the number of characters to count. This can be solved by maintaining a dictionary of the relevant characters but I’m guessing that this is too advanced for your exercise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With