Lesson 12: Mastering String Manipulation in VB2022

Working with text data, manipulating strings, and formatting text in Visual Basic programming

Key Takeaway

String manipulation is essential for processing text data in applications. VB2022 provides a comprehensive set of functions for working with strings, including concatenation, extraction, transformation, and searching operations.

Welcome to Lesson 12 of our Visual Basic 2022 Tutorial! In this lesson, you'll learn how to manipulate strings using VB2022. From basic operations like concatenation to advanced functions for searching and transforming text, you'll gain the skills needed to work effectively with text data in your applications.

Learning Objectives

  • Understand VB2022 string operators and concatenation
  • Master essential string functions (Len, Left, Right, Mid)
  • Transform text with UCase, LCase, and Trim functions
  • Search within strings using InStr
  • Work with ASCII codes using Chr and Asc
  • Implement practical string manipulation techniques
  • Create text processing applications

12.1 String Concatenation

VB.NET provides two primary operators for concatenating strings:

Addition (+)

Adds two strings together

Ampersand (&)

Concatenates strings (safer with mixed types)

12.1.1 Operator Differences

The + operator can cause errors when used with mixed data types, while the & operator automatically converts non-string values to strings:

Concatenation.vb
' Using the + operator with mixed types
Dim str1 = "Visual ", str2 = "Basic ", str3 = "2022", str As String
Dim num As Integer = 100

' This works:
str = str1 + str2 + str3 ' "Visual Basic 2022"

' This causes an error:
' str = str1 + str2 + str3 + num

' Using the & operator with mixed types
str = str1 & str2 & str3 & num ' "Visual Basic 2022100"

Best Practice

Always use the & operator for string concatenation to avoid data type conversion errors, especially when working with mixed data types.

12.2 Essential String Functions

VB2022 provides a comprehensive set of functions for string manipulation:

Len Function

Returns the length of a string

Len("String")
Len("Hello") ' Returns 5

Left Function

Extracts characters from the start of a string

Microsoft.VisualBasic.Left("String", n)
Left("Programming", 4) ' "Prog"

Right Function

Extracts characters from the end of a string

Microsoft.VisualBasic.Right("String", n)
Right("Programming", 3) ' "ing"

Mid Function

Extracts a substring from within a string

Mid("String", start, length)
Mid("Programming", 4, 5) ' "gramm"

InStr Function

Finds the position of a substring within a string

InStr(start, "MainString", "SubString")
InStr(1, "Programming", "gram") ' Returns 4

UCase & LCase

Converts strings to uppercase or lowercase

UCase("String")
LCase("String")
UCase("Hello") ' "HELLO"
LCase("WORLD") ' "world"

Trim Functions

Removes whitespace from strings

Trim(" String ")
LTrim(" String ")
RTrim(" String ")
Trim(" Hello ") ' "Hello"

Chr & Asc Functions

Converts between characters and ASCII codes

Chr(code)
Asc("Character")
Chr(65) ' "A"
Asc("A") ' 65

12.3 Practical Examples

Let's implement some practical string manipulation applications:

1 String Extractor

Extract portions of a string using Mid, Left, and Right functions:

StringExtractor.vb
Private Sub BtnExtract_Click(sender As Object, e As EventArgs) Handles BtnExtract.Click
    Dim input As String = TxtInput.Text
    
    ' Extract first 5 characters
    LblLeft.Text = Microsoft.VisualBasic.Left(input, 5)
    
    ' Extract last 5 characters
    LblRight.Text = Microsoft.VisualBasic.Right(input, 5)
    
    ' Extract middle portion (position 3 to 7)
    LblMid.Text = Mid(input, 3, 5)
End Sub

2 Case Converter

Convert text between uppercase, lowercase, and proper case:

CaseConverter.vb
Private Sub BtnConvert_Click(sender As Object, e As EventArgs) Handles BtnConvert.Click
    Dim input As String = TxtInput.Text
    
    Select Case True
        Case RdbUpper.Checked
            TxtOutput.Text = Microsoft.VisualBasic.UCase(input)
        Case RdbLower.Checked
            TxtOutput.Text = Microsoft.VisualBasic.LCase(input)
        Case RdbProper.Checked
            TxtOutput.Text = StrConv(input, VbStrConv.ProperCase)
    End Select
End Sub

3 Text Analyzer

Analyze text to count characters, words, and find substrings:

TextAnalyzer.vb
Private Sub BtnAnalyze_Click(sender As Object, e As EventArgs) Handles BtnAnalyze.Click
    Dim text As String = TxtInput.Text
    
    ' Character count
    LblCharCount.Text = "Characters: " & Len(text)
    
    ' Word count
    Dim words As String() = text.Split(" "c)
    LblWordCount.Text = "Words: " & words.Length
    
    ' Find position of search term
    Dim searchTerm As String = TxtSearch.Text
    Dim position As Integer = InStr(1, text, searchTerm)
    
    If position > 0 Then
        LblSearchResult.Text = "Found at position: " & position
    Else
        LblSearchResult.Text = "Search term not found"
    End If
End Sub

12.3.1 Name Formatter

Format names into different styles (First Last, Last First, etc.):

NameFormatter.vb
Private Sub BtnFormat_Click(sender As Object, e As EventArgs) Handles BtnFormat.Click
    Dim fullName As String = TxtFullName.Text.Trim()
    
    ' Find space position
    Dim spacePos As Integer = InStr(fullName, " ")
    
    If spacePos = 0 Then
        MessageBox.Show("Please enter first and last name separated by a space")
        Return
    End If
    
    ' Extract parts
    Dim firstName As String = Microsoft.VisualBasic.Left(fullName, spacePos - 1)
    Dim lastName As String = Microsoft.VisualBasic.Right(fullName, Len(fullName) - spacePos)
    
    ' Format based on selection
    Select Case cmbFormat.SelectedIndex
        Case 0 ' First Last
            LblResult.Text = firstName & " " & lastName
        Case 1 ' Last, First
            LblResult.Text = lastName & ", " & firstName
        Case 2 ' F. Last
            LblResult.Text = Microsoft.VisualBasic.Left(firstName, 1) & ". " & lastName
        Case 3 ' Last F.
            LblResult.Text = lastName & " " & Microsoft.VisualBasic.Left(firstName, 1) & "."
    End Select
End Sub

Output:

For input: "John Smith"
Format: "Last, First" → "Smith, John"

12.3.2 Password Generator

Generate secure passwords using string functions:

PasswordGenerator.vb
Private Sub BtnGenerate_Click(sender As Object, e As EventArgs) Handles BtnGenerate.Click
    Dim length As Integer
    
    ' Validate length input
    If Not Integer.TryParse(TxtLength.Text, length) Or length < 8 Or length > 20 Then
        MessageBox.Show("Please enter a valid password length (8-20)")
        Return
    End If
    
    ' Character sets
    Dim lower As String = "abcdefghijklmnopqrstuvwxyz"
    Dim upper As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Dim digits As String = "0123456789"
    Dim symbols As String = "!@#$%^&*()_-+=[]{}|;:,.<>?/"
    Dim allChars As String = lower & upper & digits & symbols
    
    Dim password As String = ""
    Dim rnd As New Random()
    
    ' Generate password
    For i As Integer = 1 To length
        Dim index As Integer = rnd.Next(0, Len(allChars))
        password &= Mid(allChars, index + 1, 1)
    Next
    
    ' Ensure at least one of each character type
    If InStr(password, "A") < "a" Then ' Case-insensitive check
        password = Mid(password, 1, 1) & Chr(rnd.Next(65, 91)) & Mid(password, 3)
    End If
    
    ' Display result
    TxtPassword.Text = password
End Sub

Lesson Summary

In this lesson, we've covered essential concepts about string manipulation in VB2022:

Concatenation

Using & and + operators to combine strings

Extraction

Left, Right, and Mid functions to retrieve parts of strings

Transformation

UCase, LCase, and Trim functions to modify strings

Searching

InStr function to find substrings within strings

ASCII Conversion

Chr and Asc functions to work with character codes

These skills are fundamental for building applications that process and manipulate text data. In the next lesson, we'll explore conditional logic with If..Then..Else statements.

Exercises

Practice what you've learned with these exercises:

Exercise 1: Palindrome Checker

Create a program that:

  1. Checks if a word or phrase is a palindrome (reads the same forwards and backwards)
  2. Ignores case, spaces, and punctuation
  3. Displays whether the input is a palindrome or not

Exercise 2: Email Validator

Build an application that:

  1. Validates email addresses based on common rules
  2. Checks for the presence of "@" and "."
  3. Verifies the domain extension (e.g., .com, .net, .org)
  4. Provides feedback on validation results

Exercise 3: Text Encryption

Implement a solution that:

  1. Encrypts text using a simple substitution cipher
  2. Decrypts text using the same cipher
  3. Allows the user to input text and see encrypted/decrypted results

Next Lesson

Ready to learn about conditional logic? Continue to Lesson 13: If..Then..Else in VB2022.

Related Resources

VB6 Tutorial

Mastering VB6 Programming

Explore Tutorials

Visual Basic Examples

Practical VB code samples for real-world applications

View Examples

Excel VBA Tutorial

Learn how to automate Excel by creating VBA macros

Learn More