Visual Basic (VB) String

In visual basic, String is a keyword and it is useful to represent a sequential collection of characters that is called a text. In visual basic, the String keyword is useful to create a string variable to hold the text which is a sequential collection of characters.

 

The string variables in visual basic can hold any kind of text and by using Length property we can know that the number of characters the string variable is holding based on our requirements.

Visual Basic String Declaration and Initialization

Following are the different ways of declaring and initializing the string variables using String keyword in visual basic programming language.

 

' Declare without initializing

Dim str1 As String

' Declaring and Initializing

Dim str2 As String = "Welcome to Tutlane"

Dim str3 As String = "Hello World!"

' Initialize an empty string

Dim str4 As String = String.Empty

' Initialize to null

Dim str5 As String = Nothing

' Creating a string from char

Dim letters As Char() = {"A"c, "B"c, "C"c}

Dim str6 As String = New String(letters)

If you observe the above code snippet, we created a string variables using String keyword with or without initializing a values based on our requirements.

Visual Basic String Immutability

In visual basic, the string is immutable, it means the string object cannot be modified once it created. If any changes made to the string object like add or modify an existing value, then it will simply discard the old instance in memory and create a new instance to hold the new value.

 

For example, when we create a new string variable “msg” with text “welcome”, the new instance will create on heap memory to hold this value. Now, if we make any changes to the msg variable like changing the text from “welcome” to “welcome to tutlane”, the old instance on heap memory will be simply discarded and another instance will create on the heap memory to hold the variable value instead of modifying the old instance in the memory.

 

Following is the pictorial representation of memory allocation of string in visual basic programming language.

 

Visual Basic String Memory Representation Diagram

 

In visual basic, if we perform modifications like inserting, concatenating, removing or replacing the value of an existing string for multiple times, then every time the new instance will create on heap memory to hold the new value so automatically the performance of the application will be effected.

Visual Basic Format Strings

In visual basic, we can format the string data by using Format method and embedding a placeholders in braces that will be replaced by other values at runtime.

 

Following is the example of using string Format method to determine the string content dynamically at runtime in visual basic programming language.

 

Dim name As String = "Suresh Dasari"

Dim location As String = "Hyderabad"

Dim user As String = String.Format("Name: {0}, Location: {1}", name, location)

' Output: Name: Suresh Dasari, Location: Hyderabad

If you observe the above code, we are formatting the string using Format method and replacing the placeholders in braces with required values.

Visual Basic Access Individual Characters from Strings

In visual basic, we can access the individual characters from string by using array notation with index values.

 

Following is the example of accessing the individual characters from string by specifying the index position.

 

Dim name As String = "Suresh Dasari"

For i As Integer = 0 To name.Length - 1

Console.Write(name(i))

Next

' Output: Suresh Dasari

If you observe the above example, we are looping through the characters in string using For loop and displaying the each character of string based on the index position.

Visual Basic String Example

Following is the example of declaring and initializing the strings, formatting the string value and use string literals to represent data in visual basic programming language.

 

Module Module1

    Sub Main()

        Dim firstname As String = "Suresh"

        Dim lastname As String = "Dasari"

        Dim location As String = "Hyderabad"

        Dim name As String = firstname & " " & lastname

        Console.WriteLine(name)

        Dim userInfo As String = String.Format("Name: {0}, Location: {1}", name, location)

        Console.WriteLine(userInfo)

        Dim names As String = "Suresh" & vbLf & "Rohini" & vbLf & "Trishika"

        Console.WriteLine(names)

        Dim path As String = "C:\Users\Tutlane\Documents\"

        Console.WriteLine(path)

        Dim msg As String = "Her name was ""Trishika."""

        Console.WriteLine(msg)

        Console.WriteLine(vbLf & "Press Enter Key to Exit..")

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we declared and initialized the string variables, formatted string using Format method and used a string literals to embed escape characters, etc. based on our requirements.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Suresh Dasari

Name: Suresh Dasari, Location: Hyderabad

Suresh

Rohini

Trishika

C:\Users\Tutlane\Documents\

Her name was "Trishika."

 

Press Enter Key to Exit..

This is how we can use the strings in visual basic programming language to represent the sequential collection of characters based our requirements.

Visual Basic String Properties

Following table lists the available string properties in visual basic programming language.

 

PropertyDescription
Chars It help us to get the characters from the current string object based on the specified position.
Length It return the number of characters in current String object.

Visual Basic String Methods

In visual basic, the string class contains a various methods to manipulate the string objects data based on our requirements.

 

Following table lists an important string methods available in visual basic programming language.

 

MethodDescription
Compare(String, String) It compares a two specified String objects and returns an integer that indicates their relative position in the sort order.
Concat(String, String) It concatenates two specified instances of String.
Copy(String) It creates a new instance of String with the same value as a specified String.
Format(String, Object) It replaces one or more format items in a specified string with the string representation of a specified object.
Trim() It removes all leading and trailing white-space characters from the current String object.
ToLower() It converts a given string to lowercase.
ToUpper() It converts a given string to uppercase.
Split(Char[]) It splits a string into substrings that are based on the characters in an array.

This is how we can use the strings in our applications to hold the required text in visual basic programming language.

Topics Covered