Lesson 12 ยท String Manipulation

String Manipulation

Master Visual Basic 2026's comprehensive text-processing toolkit โ€” concatenation, extraction (Left, Right, Mid), searching (InStr, Contains, IndexOf), transformation (UCase, LCase, Trim, Replace), splitting and joining, string interpolation, StringBuilder for performance, and .NET 10 improvements โ€” with GitHub Copilot assistance throughout.

Key Takeaway: Strings in VB 2026 are immutable reference types โ€” every operation creates a new string rather than modifying the original. For simple operations use the String class methods; for building strings in a loop use StringBuilder for much better performance. VB 2026 / .NET 10 adds string interpolation ($"โ€ฆ{expr}โ€ฆ") as the preferred way to build formatted strings, plus raw string literals and span-based methods for high-performance text processing.

12.1 String Concatenation

VB 2026 provides two concatenation operators: & and +. Always prefer & for string concatenation โ€” it works safely with any data type by converting it to string first. The + operator performs addition when both operands are numeric, which can cause unexpected bugs.

Concatenation.vb โ€” Visual Basic 2026
' โ”€โ”€ & operator โ€” safe, always concatenates โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim firstName As String = "Alice"
Dim lastName  As String = "Wong"
Dim fullName  = firstName & " " & lastName   ' "Alice Wong"

' โ”€โ”€ + operator โ€” risky with mixed types โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim result1 = "Score: " + 95.ToString()     ' โœ” OK โ€” explicit ToString()
Dim result2 = "Value: " & 42               ' โœ” & converts 42 to "42" automatically

' โ”€โ”€ String interpolation โ€” the modern VB 2026 way โ”€โ”€โ”€โ”€โ”€โ”€
Dim age   = 25
Dim score = 95
Dim gpa   = 3.85

lblInfo.Text = $"{firstName} {lastName} โ€” Age: {age}, Score: {score}, GPA: {gpa:F2}"
' โ†’ "Alice Wong โ€” Age: 25, Score: 95, GPA: 3.85"

' Interpolation with expressions and format specs
Dim price = 29.9D
lblPrice.Text = $"Total: {price * 1.06:C}"     ' currency format โ†’ "Total: RM31.65"
lblDate.Text  = $"Today: {DateTime.Today:dd/MM/yyyy}"

' โ”€โ”€ += to append to existing string โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim report As String = ""
report &= "Name: Alice" & vbCrLf
report &= "Score: 95"  & vbCrLf
txtReport.Text = report

12.2 Essential String Functions

๐Ÿ“ Length & Info
Len(s) / s.LengthLen("Hello") โ†’ 5
s.IsNullOrEmpty()IsNullOrEmpty("") โ†’ True
s.IsNullOrWhiteSpace()IsNullOrWhiteSpace(" ") โ†’ True
s.Chars(i)"Hello".Chars(1) โ†’ 'e'
โœ‚ Extraction
Left(s, n)Left("Hello",3) โ†’ "Hel"
Right(s, n)Right("Hello",3) โ†’ "llo"
Mid(s, start, n)Mid("Hello",2,3) โ†’ "ell"
s.Substring(i, n)"Hello".Substring(1,3) โ†’ "ell"
๐Ÿ” Searching
InStr(s, find)InStr("Hello","ll") โ†’ 3
s.IndexOf(find)"Hello".IndexOf("l") โ†’ 2 (0-based)
s.Contains(sub)"Hello".Contains("ell") โ†’ True
s.StartsWith(p)"Hello".StartsWith("He") โ†’ True
s.EndsWith(p)"Hello".EndsWith("lo") โ†’ True
๐Ÿ”„ Transformation
UCase(s) / s.ToUpper()"hello" โ†’ "HELLO"
LCase(s) / s.ToLower()"HELLO" โ†’ "hello"
StrConv(s, ProperCase)"hello world" โ†’ "Hello World"
s.Replace(old, new)"cat".Replace("c","b") โ†’ "bat"
s.ToTitleCase().NET 10: "hello" โ†’ "Hello"
โœ‚ Trim & Pad
Trim(s) / s.Trim()" hi " โ†’ "hi"
LTrim(s) / s.TrimStart()" hi " โ†’ "hi "
RTrim(s) / s.TrimEnd()" hi " โ†’ " hi"
s.PadLeft(n)"42".PadLeft(5) โ†’ " 42"
s.PadRight(n, char)"A".PadRight(4,'.')
๐Ÿ”€ Split & Join
s.Split(","c)"a,b,c".Split(",") โ†’ {"a","b","c"}
String.Join(sep, arr)Join("-",{"a","b"}) โ†’ "a-b"
s.Split(delims, opts)Remove empty entries
Environment.NewLinePlatform-safe line break

Important Difference: VB Functions vs .NET Methods

VB 2026 supports both the classic VB string functions (Left, Mid, InStr, Len) and .NET String methods (.Substring(), .IndexOf(), .Length). The key difference is indexing: VB functions use 1-based positions; .NET methods use 0-based positions.

VBvsNET.vb โ€” Index comparison
Dim s = "Visual Basic 2026"

' โ”€โ”€ VB functions โ€” 1-based โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim vbLen   = Len(s)                  ' 17
Dim vbLeft  = Left(s, 6)             ' "Visual" (first 6 chars)
Dim vbRight = Right(s, 4)            ' "2026" (last 4 chars)
Dim vbMid   = Mid(s, 8, 5)           ' "Basic" (start at pos 8, take 5)
Dim vbFind  = InStr(s, "Basic")       ' 8 (1-based position)

' โ”€โ”€ .NET String methods โ€” 0-based โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim netLen    = s.Length              ' 17
Dim netLeft   = s.Substring(0, 6)    ' "Visual" (start 0, length 6)
Dim netRight  = s.Substring(s.Length - 4)   ' "2026"
Dim netMid    = s.Substring(7, 5)    ' "Basic" (0-based start = 7)
Dim netFind   = s.IndexOf("Basic")   ' 7 (0-based index)

' โ”€โ”€ Consistency tip: pick one style and stick to it โ”€โ”€โ”€โ”€
' .NET methods work everywhere; VB functions need Imports Microsoft.VisualBasic
โš  1-Based vs 0-Based โ€” The #1 String Bug

Mid("Hello", 1, 3) returns "Hel" (VB, starts at 1). "Hello".Substring(0, 3) also returns "Hel" (.NET, starts at 0). Mixing styles causes off-by-one errors. VB 2026 best practice: use .NET methods (.Substring(), .IndexOf()) for new code โ€” they work everywhere including Blazor and MAUI. Use VB functions (Mid, InStr) only when working with legacy VB code.

Try It โ€” Simulation 12.1: String Extraction Explorer

Type a string and use Left/Right/Mid/Substring to extract portions โ€” the visualiser highlights exactly which characters are selected.

String Extraction Explorer
Input string (txtInput):
Function:
n / length:
start pos:

12.3 Searching Strings

StringSearch.vb โ€” Visual Basic 2026
Dim email = "[email protected]"

' โ”€โ”€ Contains / StartsWith / EndsWith โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
If email.Contains("@") Then
    lblResult.Text = "Valid email format"
End If

If email.EndsWith(".com") Then
    lblDomain.Text = "Commercial domain"
End If

' โ”€โ”€ IndexOf โ€” find position (0-based), -1 if not found โ”€
Dim atPos  = email.IndexOf("@")           ' 10
Dim dotPos = email.LastIndexOf(".")         ' 18 (last dot)

' Extract username and domain using IndexOf
If atPos > 0 Then
    Dim username = email.Substring(0, atPos)           ' "alice.wong"
    Dim domain   = email.Substring(atPos + 1)           ' "example.com"
    lblUser.Text   = $"User: {username}"
    lblDomain.Text = $"Domain: {domain}"
End If

' โ”€โ”€ InStr โ€” VB-style search (1-based, 0 if not found) โ”€
Dim pos = InStr(email, "@")              ' 11 (1-based)
If pos > 0 Then
    Dim user = Left(email, pos - 1)        ' "alice.wong"
End If

' โ”€โ”€ Case-insensitive comparison โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
If String.Compare(email, "[email protected]", True) = 0 Then
    ' Third arg True = ignore case
End If

' โ”€โ”€ OrdinalIgnoreCase (most reliable for comparisons) โ”€โ”€
If email.Equals("[email protected]", StringComparison.OrdinalIgnoreCase) Then
    lblResult.Text = "Emails match (case-insensitive)"
End If

12.4 Transforming Strings

StringTransform.vb โ€” Visual Basic 2026
Dim input = "  Hello, Visual Basic 2026!  "

' โ”€โ”€ Case conversion โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim upper  = input.ToUpper()           ' "  HELLO, VISUAL BASIC 2026!  "
Dim lower  = input.ToLower()           ' "  hello, visual basic 2026!  "
Dim proper = StrConv(input, VbStrConv.ProperCase)   ' "  Hello, Visual Basic 2026!  "

' โ”€โ”€ Trim whitespace โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim trimmed  = input.Trim()            ' "Hello, Visual Basic 2026!" (both ends)
Dim trimLeft = input.TrimStart()       ' removes leading spaces only
Dim trimEnd  = input.TrimEnd()         ' removes trailing spaces only
' Good practice: always Trim() user input from TextBoxes
Dim name = txtName.Text.Trim()

' โ”€โ”€ Replace โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim phone   = "012-345-6789"
Dim noHyphen = phone.Replace("-", "")   ' "0123456789" โ€” remove all hyphens
Dim masked   = phone.Replace(phone.Substring(3, 3), "***")  ' mask middle digits

' โ”€โ”€ PadLeft / PadRight โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim id      = "42"
Dim padded  = id.PadLeft(6, "0"c)        ' "000042" โ€” zero-pad to 6 digits
Dim padR    = "Alice".PadRight(12, "."c)  ' "Alice......." โ€” table alignment

' โ”€โ”€ Reverse a string (no built-in, use LINQ) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim rev = New String(input.Trim().Reverse().ToArray())
' โ†’ "!6202 cisaB lausiV ,olleH"
Try It โ€” Simulation 12.2: String Transformer

Apply transformation functions to your text โ€” case conversion, trim, replace, pad, and reverse.

String Transformer
Input string:
Find:
Replace with:
Total width:
Pad char:

12.5 Split and Join

Split() breaks a string into an array using a delimiter โ€” perfect for parsing CSV data, user input lists, file paths, and email addresses. String.Join() does the reverse, assembling an array back into a single string with a separator.

SplitJoin.vb โ€” Visual Basic 2026
' โ”€โ”€ Split by single delimiter โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim csv     = "Alice,Bob,Charlie,Diana,Eve"
Dim names() = csv.Split(","c)               ' {"Alice","Bob","Charlie","Diana","Eve"}

For Each name As String In names
    lstNames.Items.Add(name)
Next

' โ”€โ”€ Split with multiple delimiters โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim data    = "Name:Alice;Age:25;City:KL"
Dim pairs() = data.Split({";"c, ":"c})       ' {"Name","Alice","Age","25","City","KL"}

' โ”€โ”€ Split with options โ€” remove empty entries โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim messy   = "one,,two,,,three"
Dim clean() = messy.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
' {"one","two","three"} โ€” empty parts removed

' โ”€โ”€ Parse CSV line into structured data โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim record  = "STU001,Alice Wong,85,92,78"
Dim fields  = record.Split(","c)
Dim id      = fields(0)              ' "STU001"
Dim student = fields(1)             ' "Alice Wong"
Dim mark1   = CInt(fields(2))        ' 85

' โ”€โ”€ Join โ€” reverse of split โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim parts() = {"Visual", "Basic", "2026"}
Dim joined  = String.Join(" ", parts)    ' "Visual Basic 2026"
Dim path    = String.Join("/", {"C:", "Users", "Alice", "Documents"})
' "C:/Users/Alice/Documents"

' โ”€โ”€ Split path components โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim filePath  = "C:\Users\Alice\report.docx"
Dim pathParts = filePath.Split("\"c)
Dim fileName  = pathParts(pathParts.Length - 1)   ' "report.docx"
Try It โ€” Simulation 12.3: Split & Join Lab

Enter a delimited string, choose a delimiter, split it apart โ€” then re-join with a different separator.

Split & Join Lab
Input string:
Split delimiter:
Join with separator:

12.6 StringBuilder โ€” High-Performance String Building

Because strings are immutable, every &= in a loop creates a new string object and copies all previous characters. For a loop of N iterations this is O(Nยฒ) work. StringBuilder uses a mutable internal buffer โ€” appending is O(1) amortized. Use it whenever you build a string inside a loop.

StringBuilder.vb โ€” Visual Basic 2026
Imports System.Text

' โ”€โ”€ The SLOW way โ€” creates thousands of string objects โ”€
Dim report As String = ""
For i = 1 To 1000
    report &= $"Line {i}: data{vbCrLf}"    ' โœ˜ slow โ€” 1000 new string objects
Next

' โ”€โ”€ The FAST way โ€” StringBuilder with mutable buffer โ”€โ”€โ”€
Dim sb As New StringBuilder()
For i = 1 To 1000
    sb.AppendLine($"Line {i}: data")        ' โœ” fast โ€” appends to internal buffer
Next
Dim result = sb.ToString()                  ' one string at the end

' โ”€โ”€ StringBuilder methods โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim sb2 As New StringBuilder("Hello")
sb2.Append(", World")                       ' "Hello, World"
sb2.AppendLine("!")                          ' appends + newline
sb2.Insert(5, " Beautiful")                ' "Hello Beautiful, World\n!"
sb2.Replace("World", "VB 2026")            ' find/replace in buffer
sb2.Remove(0, 6)                            ' remove 6 chars from pos 0
Dim len = sb2.Length                          ' current length
sb2.Clear()                                   ' reset to empty

' โ”€โ”€ Practical: generate HTML table โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim html As New StringBuilder()
html.AppendLine("<table>")
For Each row As String In dataRows
    html.AppendLine($"  <tr><td>{row}</td></tr>")
Next
html.AppendLine("</table>")
txtOutput.Text = html.ToString()

12.7 New in VB 2026 / .NET 10

NewStringFeatures.vb โ€” Visual Basic 2026 / .NET 10
' โ”€โ”€ Raw string literals (multi-line, no escape needed) โ”€
Dim json = """
{
    "name": "Alice",
    "age": 25,
    "city": "Kuala Lumpur"
}
"""
' Triple quotes โ€” no need to escape internal quotes

' โ”€โ”€ String.Equals with OrdinalIgnoreCase โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim isMatch = "Hello".Equals("hello", StringComparison.OrdinalIgnoreCase)   ' True

' โ”€โ”€ Span-based methods โ€” zero-allocation parsing โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Dim line   = "Alice,25,KL".AsSpan()
Dim comma1 = line.IndexOf(","c)
Dim name   = line.Slice(0, comma1).ToString()   ' "Alice" โ€” no string allocation

' โ”€โ”€ String.Create โ€” efficient string construction โ”€โ”€โ”€โ”€โ”€โ”€
Dim id = String.Create(8, "user", Sub(span, prefix)
    prefix.CopyTo(span)
    "0001".CopyTo(span.Slice(prefix.Length))
End Sub)
' id = "user0001" โ€” no intermediate strings

' โ”€โ”€ SearchValues โ€” fast multi-char scanning (.NET 10) โ”€โ”€
Dim digits   = System.Buffers.SearchValues.Create("0123456789")
Dim phone    = "Call 012-345-6789 now"
Dim firstNum = phone.AsSpan().IndexOfAny(digits)    ' 5 โ€” first digit position

' โ”€โ”€ String.IsNullOrWhiteSpace โ€” essential input guard โ”€โ”€
If String.IsNullOrWhiteSpace(txtName.Text) Then
    lblError.Text = "Name is required"
    Return
End If
๐Ÿ’ก VB 2026 String Best Practices
  • Always Trim() user input from TextBoxes before any processing
  • Use String.IsNullOrWhiteSpace() instead of = "" to guard against Nothing and whitespace-only input
  • Prefer string interpolation ($"โ€ฆ{expr}โ€ฆ") over & chains โ€” more readable and slightly faster in .NET 10
  • Use StringBuilder when building strings in a loop with more than ~10 iterations
  • Use StringComparison.OrdinalIgnoreCase for case-insensitive comparisons โ€” it is faster and culturally safe
  • Use & (not +) for string concatenation to avoid type confusion bugs
Try It โ€” Simulation 12.4: Email and Name Parser

Parse an email address into components using IndexOf, Substring, and Split. Also parse a full name into first/last using string functions.

Email & Name Parser
Email Parser
Email address:
Name Formatter
Full name (first last):
Try It โ€” Simulation 12.5: Complete String Analyser

Enter any text and get a full analysis โ€” length, word count, character frequencies, InStr search, and palindrome detection.

String Analyser
Text to analyse:
Search for:

12.8 GitHub Copilot โ€” String Assistance

GitHub Copilot โ€” CSV Parser
You typed: ' Parse a CSV line "id,name,age,score" from txtCSV. Validate each field, then display in 4 Labels'
' Parse a CSV line "id,name,age,score" from txtCSV. Validate each field, then display in 4 Labels
Dim line   = txtCSV.Text.Trim()
Dim fields = line.Split(","c)

If fields.Length < 4 Then
    lblError.Text = $"โš  Expected 4 fields, got {fields.Length}"
    Return
End If

Dim id    = fields(0).Trim()
Dim name  = fields(1).Trim()
Dim age   As Integer
Dim score As Double

If Not Integer.TryParse(fields(2).Trim(), age) Then
    lblError.Text = "โš  Age must be a whole number."
    Return
End If
If Not Double.TryParse(fields(3).Trim(), score) Then
    lblError.Text = "โš  Score must be a number."
    Return
End If

lblID.Text    = $"ID: {id}"
lblName.Text  = $"Name: {name}"
lblAge.Text   = $"Age: {age}"
lblScore.Text = $"Score: {score:F1}"
GitHub Copilot โ€” Password Strength Checker
You typed: ' Check password strength: at least 8 chars, contains uppercase, lowercase, digit, and special char. Show strength as Weak/Fair/Strong/Very Strong'
' Check password strength: at least 8 chars, contains uppercase, lowercase, digit, and special char. Show strength as Weak/Fair/Strong/Very Strong
Dim pwd = txtPassword.Text

Dim hasUpper   = pwd.Any(Function(c) Char.IsUpper(c))
Dim hasLower   = pwd.Any(Function(c) Char.IsLower(c))
Dim hasDigit   = pwd.Any(Function(c) Char.IsDigit(c))
Dim hasSpecial = pwd.Any(Function(c) Not Char.IsLetterOrDigit(c))
Dim isLong     = pwd.Length >= 8

Dim score = ({isLong, hasUpper, hasLower, hasDigit, hasSpecial}).Count(Function(b) b)

Dim strength = Select Case score
    Case 0, 1  : "Weak"
    Case 2, 3  : "Fair"
    Case 4     : "Strong"
    Case Else   : "Very Strong"
End Select

lblStrength.Text = $"Strength: {strength} ({score}/5 criteria met)"
๐Ÿ’ก Copilot Chat Prompts for This Lesson

Try these in the Copilot Chat panel while working with strings:

  • "Validate a Malaysian phone number format (012-345-6789) using Contains, StartsWith, and Length checks"
  • "Parse a full name 'firstname middlename lastname' and create initials like 'A.M.W.'"
  • "Build a word frequency counter for the text in a RichTextBox using Split and Dictionary(Of String, Integer)"
  • "Use StringBuilder to generate a formatted report of student marks with name, score, and grade columns"

๐Ÿ“˜ Lesson Summary

  • Use & (not +) for string concatenation โ€” it safely converts any type to String automatically. Prefer string interpolation ($"โ€ฆ{expr}โ€ฆ") for readable, formatted strings.
  • VB functions (Left, Right, Mid, InStr) use 1-based positions. .NET methods (Substring, IndexOf) use 0-based positions โ€” never mix the two styles in the same expression.
  • Contains(), StartsWith(), EndsWith() are the most readable search methods. Use IndexOf() when you need the actual position; it returns -1 if not found.
  • Always call .Trim() on user input from TextBoxes. Use String.IsNullOrWhiteSpace() as the guard check โ€” it handles Nothing, empty string, and whitespace-only strings.
  • Split(","c) converts a delimited string to an array. String.Join(sep, array) reverses this. Use StringSplitOptions.RemoveEmptyEntries to clean up empty tokens.
  • Use StringBuilder in loops โ€” it avoids creating Nยฒ string copies. Call .AppendLine(), .Insert(), .Replace(), and .ToString() at the end.
  • VB 2026 / .NET 10 adds raw string literals (triple-quoted, no escape needed), Span-based methods for zero-allocation parsing, and SearchValues for fast multi-character scanning.
  • For case-insensitive comparisons use StringComparison.OrdinalIgnoreCase โ€” it is faster and avoids culture-specific bugs (e.g. Turkish lowercase ฤฐ).

Exercises

Exercise 12.1 โ€” Text Processing App

  • Build a form with a multiline TextBox for input and a Label/TextBox area for output
  • Add buttons for: ToUpper, ToLower, ProperCase, Trim All Lines, Count Words, Count Characters (no spaces)
  • Add a Find/Replace section with two TextBoxes and a Replace button that uses .Replace()
  • Display word count by splitting on spaces and using StringSplitOptions.RemoveEmptyEntries
  • Copilot challenge: Ask Copilot to "add a character frequency table showing how many times each letter appears, sorted by frequency"

Exercise 12.2 โ€” CSV Student Record Parser

  • Let the user paste a CSV line in the format: ID,Name,Math,Science,English
  • Use Split(","c) to parse the fields. Validate each field with TryParse where appropriate
  • Calculate the average mark and display a formatted report using string interpolation
  • Use PadRight() on the name column and PadLeft() on number columns for table alignment
  • Copilot challenge: Ask Copilot to "let the user paste multiple CSV lines and process them all into a ListBox report"

Exercise 12.3 โ€” Password Strength Meter

  • Build a password input TextBox that checks strength in real-time as the user types
  • Check for: Length โ‰ฅ 8, Has uppercase, Has lowercase, Has digit, Has special character
  • Show a coloured ProgressBar or label: Weak (red), Fair (orange), Strong (yellow), Very Strong (green)
  • Use Char.IsUpper(), Char.IsLower(), Char.IsDigit(), and Char.IsLetterOrDigit()
  • Copilot challenge: Ask Copilot to "add a 'Show/Hide password' CheckBox that toggles between PasswordChar = '*' and empty"

Next: Lesson 13 โ€” If..Then..Else

Learn to control program flow with conditional logic โ€” If..Then, If..Then..Else, ElseIf chains, nested conditions, and the ternary If() operator in Visual Basic 2026.

Continue โฏ

Related Resources


Featured Books

Visual Basic 2026 Made Easy โ€” Second Edition

Visual Basic 2026 Made Easy โ€” Second Edition

by Dr. Liew Voon Kiong

Learn VB.NET with Visual Studio 2026 and .NET 10: Windows Forms, Databases, LINQ, Async Programming, Practical Projects, and GitHub Source Code

View on Amazon โ†’ Kindle Edition โ†’
Visual Basic 2026 Made Easy

Visual Basic 2026 Made Easy

by Dr. Liew Voon Kiong

48 fully-explained code examples spanning VB6 through VB.NET โ€” ideal for building real-world applications.

View on Amazon โ†’ Kindle Edition โ†’
Advanced Visual Basic 2026 Programming, Volume 1

Advanced Visual Basic 2026 Programming, Volume 1

by Dr. Liew Voon Kiong

Professional VB.NET Engineering, Object Modelling, Generics, Events, Design Patterns, and LINQ

View on Amazon โ†’ Kindle Edition โ†’