Iterating over the characters in a string

Visual Basic .NET strings support the For Each statement, so you can iterate over each individual character as follows:

Dim s As String = "ABCDE"Dim c As CharFor Each c In s    Console.Write(c & ".")       ' => A.B.C.D.E.Next

However, you should bear in mind that For Each loops on string characters aren’t optimized. The following solution, that uses the Chars property, is 2-5 times faster:

Dim i As IntegerFor i = 0 To s.Length - 1    Console.Write(s.Chars(i) & ".")       ' => A.B.C.D.E.Next

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: