Reading — step 1 of 5
Learn
~2 min readSubs, Functions, Arrays
VB.NET strings are .NET String objects — same as C#. Plus VB-specific functions like Mid, Left, Right (legacy from VB6).
Concatenation
Dim s = "hello" & " " & "world" ' & is the canonical concat
Dim t = "hello" + " " + "world" ' + works but ambiguous
s &= "!" ' append
Use & — + between two numerics still adds. Mixing types triggers conversions.
Length and indexing
Dim s = "hello"
s.Length ' 5
s(0) ' "h" (1-char string in VB.NET .NET 4.0+; previously Char)
s.Substring(1, 3) ' "ell" (start, length)
s.Substring(2) ' "llo" (from index to end)
Modern .NET methods
s.ToUpper()
s.ToLower()
s.Trim()
s.IndexOf("l") ' 2
s.Contains("ell") ' True
s.StartsWith("hello")
s.EndsWith("o")
s.Replace("l", "L") ' "heLLo"
s.Split(" "c) ' array of substrings ("c" suffix = Char literal)
String.Join(",", {"a", "b", "c"}) ' "a,b,c"
Legacy VB6-style functions
Still available, mostly for VB6 compatibility:
Mid(s, 2, 3) ' "ell" (1-indexed!)
Left(s, 3) ' "hel"
Right(s, 2) ' "lo"
Len(s) ' 5
UCase(s) ' "HELLO"
LCase(s) ' "hello"
Beware: Mid is 1-indexed; Substring is 0-indexed. Pick one style and stick with it.
String interpolation
Dim name = "Ada"
Dim age = 36
Dim msg = $"{name} is {age} years old"
' "Ada is 36 years old"
Dim formatted = $"{age:D5}" ' "00036" — D5 = 5-digit decimal
Dim money = $"{99.5:C}" ' "$99.50" (locale-dependent)
The $"..." is the same as C#'s string interpolation.
String.Format
Dim msg = String.Format("{0} is {1} years old", name, age)
Dim padded = String.Format("{0,10}", name) ' right-aligned, 10 chars
Dim leftPadded = String.Format("{0,-10}|", name) ' left-aligned
Dim formatted = String.Format("{0:N2}", 1234.567) ' "1,234.57"
Format specifiers: D (decimal), N (number with separators), C (currency), P (percent), F2 (2-decimal float), X (hex).
Constants
vbCrLf— Windows newline (\r\n)vbLf— Unix newlinevbTab— tabvbNullChar— NUL
String builder for performance
Imports System.Text
Dim sb As New StringBuilder()
For i = 1 To 1000
sb.Append(i.ToString())
sb.Append(",")
Next
Dim result = sb.ToString()
Much faster than &= in loops — string concat allocates a new string each time.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…