Chuyển đến nội dung

Bài 7 · Syntax and Types

Strings and Text

Work with text in Visual Basic .NET: immutable strings, concatenation, interpolation, formatting, searching, splitting, comparing, StringBuilder, Char methods and culture-safe conversions.

Text handling is part of almost every program: names, messages, file contents, reports. In .NET a String is a sequence of UTF-16 characters and, importantly, it is immutable: methods never change a string, they return a new one. This lesson covers building, formatting, searching and comparing strings in VB.NET, plus StringBuilder for heavy concatenation. Listings are VB.NET (read-only) and the runnable blocks are labelled C# stand-ins calling the same System.String members.

Creating strings

VB
Dim a As String = "Hello"
Dim b As String = "She said ""hi"""      ' doubled quote = one quote character
Dim c As String = ""                      ' empty string
Dim d As String = String.Empty            ' same thing
Dim e As String = New String("-"c, 10)    ' "----------"
Dim path = "C:\Users\Ada"                 ' backslashes need no escaping
Dim multi = "Line 1" & vbCrLf & "Line 2"  ' vbCrLf, vbTab, vbLf constants

A literal of one character followed by c (like "-"c) is a Char. A string literal may also continue over several lines (the line breaks become part of the text), but vbCrLf makes the intent clearer.

Joining and interpolating

VB
Dim first = "Ada", last = "Lovelace"
Dim full1 = first & " " & last                    ' concatenation
Dim full2 = $"{first} {last}"                     ' interpolation
Dim due As Date = #3/1/2025#
Dim line  = $"Total: {1234.5:N2} | Due: {due:yyyy-MM-dd}"
Dim aligned = $"{first,-10}|{last,10}|"           ' alignment: left 10, right 10
Dim legacy = String.Format("{0} {1}", first, last)

Inside {} you can write any expression, a comma plus a width for alignment (negative = left aligned), and a colon plus a format string: N2 (number with thousands separator and 2 decimals), C (currency), P1 (percent), D5 (zero-padded integer), yyyy-MM-dd (date), HH:mm (time).

C# Stand-in (C#): interpolation, alignment and format strings

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Common members

Strings are indexed from 0. Length is the number of characters.

VB
Dim s As String = "  Visual Basic .NET  "
Console.WriteLine(s.Length)               ' 21
Console.WriteLine(s.Trim())               ' "Visual Basic .NET"
Console.WriteLine(s.ToUpper())
Console.WriteLine(s.Trim().Substring(0, 6))  ' "Visual"
Console.WriteLine(s.Contains("Basic"))       ' True
Console.WriteLine(s.IndexOf("Basic"))        ' 9
Console.WriteLine(s.Replace("Basic", "Fun"))
Console.WriteLine(s.Trim().StartsWith("Vis")) ' True
Console.WriteLine("a,b,c".Split(","c).Length)  ' 3
Console.WriteLine(String.Join("-", {"x", "y", "z"}))  ' x-y-z
Console.WriteLine("7".PadLeft(3, "0"c))      ' 007
Console.WriteLine("abc"(1))                  ' b  (indexer returns a Char)

IndexOf returns -1 when nothing is found. Substring(start, length) takes a start index and a length, not an end index. Remember that none of these modify s.

C# Stand-in (C#): searching, slicing and splitting

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Comparing strings

= compares string contents in VB (it calls String.Equals), unlike reference comparison. By default it is case-sensitive under Option Compare Binary. For explicit control use the overloads:

VB
Dim x = "straße", y = "STRASSE"
Console.WriteLine("abc" = "ABC")                                       ' False
Console.WriteLine(String.Equals("abc", "ABC", StringComparison.OrdinalIgnoreCase))  ' True
Console.WriteLine(String.Compare("apple", "banana"))                   ' negative number
Console.WriteLine("apple".CompareTo("apple"))                          ' 0
Console.WriteLine(String.IsNullOrEmpty(Nothing))                       ' True
Console.WriteLine(String.IsNullOrWhiteSpace("   "))                    ' True

Use StringComparison.Ordinal or OrdinalIgnoreCase for identifiers and keys, and culture-aware comparison (CurrentCulture) only for text shown to people. Guard against Nothing with String.IsNullOrEmpty or IsNullOrWhiteSpace before calling instance methods.

StringBuilder for repeated edits

Each &= in a loop allocates a new string. For hundreds or thousands of appends, use System.Text.StringBuilder:

VB
Dim sb As New System.Text.StringBuilder()
For i As Integer = 1 To 5
    sb.Append(i).Append(","c)
Next
sb.Length -= 1                 ' remove the trailing comma
Console.WriteLine(sb.ToString())   ' 1,2,3,4,5
C# Stand-in (C#): StringBuilder and immutability

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Chars and text tests

A Char is a single UTF-16 code unit. Char.IsLetter, Char.IsDigit, Char.IsWhiteSpace, Char.ToUpper and similar work per character, and you can loop over a string with For Each ch As Char In text.

VB
Dim letters = 0, digits = 0
For Each ch As Char In "Room 42, floor 3"
    If Char.IsLetter(ch) Then letters += 1
    If Char.IsDigit(ch) Then digits += 1
Next
Console.WriteLine($"{letters} letters, {digits} digits")   ' 9 letters, 3 digits

Common mistakes

  • Expecting s.ToUpper() to change s. Assign the result: s = s.ToUpper().
  • Passing an end index to Substring. The second argument is a length.
  • Using culture-dependent formatting for data meant for machines. Pass CultureInfo.InvariantCulture when writing files or protocols.
  • Concatenating in big loops without StringBuilder.
  • Calling methods on a Nothing string.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does the doubled quote in "She said ""hi""" produce?

    In a VB string literal a doubled quote represents one quote character.
  2. 2. What does "Hello".Substring(1, 3) return?

    Substring(start, length) starts at index 1 and takes 3 characters: e, l, l.
  3. 3. Why is a StringBuilder better than s &= x inside a loop of 100,000 iterations?

    String is immutable, so repeated concatenation copies the text each time; StringBuilder appends in place.
  4. 4. Which test is safest for a String that might be Nothing or only spaces?

    IsNullOrWhiteSpace handles Nothing, empty and whitespace-only strings without throwing.

Summary

  • Strings are immutable, zero-indexed sequences of UTF-16 characters; every method returns a new string.
  • Join with &, interpolate with $"{x,10:N2}", and use format strings for numbers and dates.
  • Learn the core members: Trim, Substring, IndexOf, Contains, Replace, Split, Join, PadLeft.
  • Compare with explicit StringComparison values; guard against Nothing.
  • Use StringBuilder for many appends, and Char methods for per-character checks.

Next: Option Strict and Conversions

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.