VB.NET Loop Over String: For and For Each

The VB.NET programming language

You want to loop over the characters in a String instance in your VB.NET program. Using the For and For Each loops, we can access each individual character and make a decision on its value. We reveal the syntax for looping over individual characters in strings.

Example

Note

To begin, this program declares a string reference that contains the letters "perls". Next, the For Each loop is used; it declares a variable for the loop ('element') and uses the For Each... As... In... syntax. The For loop is next: it uses the For... As... To... syntax. Please notice how the value after To (input.Length - 1) has one subtracted from the max: this means the maximum index is one less than the length.

This VB program uses the For and For Each loops on a String Dim.

Program that loops over strings [VB.NET]

Module Module1
    Sub Main()
	' Input string.
	Dim input As String = "perls"

	Console.WriteLine("-- For Each --")

	' Use For Each loop on string.
	For Each element As Char In input
	    Console.WriteLine(element)
	Next

	Console.WriteLine("-- For --")

	' Use For loop on string.
	For i As Integer = 0 To input.Length - 1
	    Dim c As Char = input(i)
	    Console.WriteLine(c)
	Next

	Console.ReadLine()
    End Sub
End Module

Output

-- For Each --
p
e
r
l
s
-- For --
p
e
r
l
s

Results. In both programs, the characters in the input string were accessed separately and printed the screen. In the For loop, the Char must be acquired through an element indexing expression (input(i)); this is because the For loop has no enumeration variable like the For Each loop.

Summary

Looping over the characters in a String represents an essential piece of functionality for many algorithms implemented in the VB.NET language. You can use this style of code to test for invalid characters, to search for a certain sequence of characters, or to build up a separate data structure based on the characters encountered.

String Notes
.NET