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:
' 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
Left Function
Extracts characters from the start of a string
Right Function
Extracts characters from the end of a string
Mid Function
Extracts a substring from within a string
InStr Function
Finds the position of a substring within a string
UCase & LCase
Converts strings to uppercase or lowercase
LCase("String")
LCase("WORLD") ' "world"
Trim Functions
Removes whitespace from strings
LTrim(" String ")
RTrim(" String ")
Chr & Asc Functions
Converts between characters and ASCII codes
Asc("Character")
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:
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:
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:
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.):
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:
Format: "Last, First" → "Smith, John"
12.3.2 Password Generator
Generate secure passwords using string functions:
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:
- Checks if a word or phrase is a palindrome (reads the same forwards and backwards)
- Ignores case, spaces, and punctuation
- Displays whether the input is a palindrome or not
Exercise 2: Email Validator
Build an application that:
- Validates email addresses based on common rules
- Checks for the presence of "@" and "."
- Verifies the domain extension (e.g., .com, .net, .org)
- Provides feedback on validation results
Exercise 3: Text Encryption
Implement a solution that:
- Encrypts text using a simple substitution cipher
- Decrypts text using the same cipher
- 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

Visual Basic 2022 Made Easy
The ultimate beginner-friendly guide for mastering Windows-based application development using Visual Basic in Visual Studio 2022. Whether you're a student, teacher, hobbyist, or self-learner, this book offers a clear, step-by-step approach to help you get started with ease.
What You'll Learn:
- String manipulation techniques
- Text processing and validation
- Regular expressions for advanced matching
- File I/O operations with text
- Practical text-based applications

Mastering Excel VBA 365
Your ultimate step-by-step guide to automating tasks, building macros, and creating powerful applications within Microsoft Excel 365. Whether you're a student, business professional, or aspiring programmer, this comprehensive handbook will help you unlock the full potential of Excel's VBA.
What You'll Learn:
- String functions in Excel VBA
- Text parsing and extraction
- Data cleaning techniques
- Report generation
- Automated text processing