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?
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:
As for counting, simply have separate counter variables (
eCount As Integeretc.) for each character and increment them whencequals 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.