C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: The For-loop is next—it uses the For, As, To syntax. This is the standard loop syntax in VB.NET.
Note: The value after To (input.Length - 1) has one subtracted from the max. This means the maximum index is one less than the length.
Characters: The characters in the input string were accessed separately and printed the screen.
Get char: In the For-loop, we get the Char with an element indexing expression (input(i)).
CharVB.NET program that loops over strings
Module Module1
Sub Main()
' Input string.
Dim input As String = "Codex"
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
Version 1: The Length of the string is accessed directly in the loop bounds (we use a For-loop here).
Version 2: A local variable (length) is used to store the length of the string. We then access that in the loop expression.
VB.NET program that tests Length locals, loop bounds
Module Module1
Sub Main()
Dim m As Integer = 10000000
Dim s1 As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To m - 1
' Version 1: do not store length in local variable.
A()
Next
s1.Stop()
Dim s2 As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To m - 1
' Version 2: store length in local.
B()
Next
s2.Stop()
Dim u As Integer = 1000000
Console.WriteLine(((s1.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns"))
Console.WriteLine(((s2.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns"))
End Sub
Sub A()
Dim value As String = "birds of a feather"
Dim sum As Integer = 0
For i As Integer = 0 To value.Length - 1
If value(i) = "a" Then
sum += 1
End If
Next
End Sub
Sub B()
Dim value As String = "birds of a feather"
Dim sum As Integer = 0
Dim lengthCache As Integer = value.Length - 1
For i As Integer = 0 To lengthCache
If value(i) = "a" Then
sum += 1
End If
Next
End Sub
End Module
Output
294.88 ns Access length in For-statement (Faster)
297.07 ns Use local variable for length