Iterate Over All the Characters in a String

Problem

You want to examine each character in a string individually.

Solution

Use a For. . .Next loop that counts to the end of string, and examine the String.Chars property in each pass, or use For Each. . .Next syntax to walk through the string one character at a time.

Discussion

Iterating over the characters in a string is fairly straightforward, although there is more than one approach. One option is to use a For. . .Next loop that continues until the end of the string. You begin at position 0 and end on the last character, where the position equals String.Length - 1. In each pass through the loop, you retrieve the corresponding character from the String.Chars indexed property.

Dim i As Integer For i = ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.