Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through characters in a string in VB.NET

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?

like image 771
Timothy Coetzee Avatar asked Nov 06 '12 12:11

Timothy Coetzee


People also ask

What is looping in VB net?

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.

What is String () in VB?

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.

How do I loop through a string in Excel?

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.


1 Answers

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.

like image 89
Konrad Rudolph Avatar answered Sep 28 '22 08:09

Konrad Rudolph