VB.NET Substring Method with EXAMPLE

⚡ Smart Summary

VB.Net Substring extracts a portion of a String by specifying a starting index and an optional length. The method belongs to the String class, counts characters from zero, and returns a brand-new String without altering the original.

  • 🔢 Zero-based index: The Substring method counts characters from index 0, so the first letter of a String sits at position zero.
  • ☑️ Two overloads: Passing one argument returns everything from that index onward, while two arguments return a fixed number of characters.
  • ✂️ Extract by position: Combine Substring with IndexOf or LastIndexOf to capture the text before or after a specific character.
  • ⚠️ Safe indexing: A negative or out-of-range index throws an ArgumentOutOfRangeException, so validate values before calling the method.
  • 🔤 Immutable result: Substring returns a new String and leaves the source String unchanged, matching the immutability of .NET strings.
  • 🤖 AI assistance: GitHub Copilot and IntelliCode in Visual Studio 2026 suggest correct Substring calls and flag out-of-range indexes as you type.

VB.Net Substring

What is a Substring?

The Substring function is used to obtain a part of a specified string. This method is defined in the String class of Microsoft VB.Net. You have to specify the start index from which the String will be extracted. The String will be extracted from that index up to the length that you specify.

Before extracting text, it helps to understand the syntax that the Substring method expects.

Syntax of Substring

The function accepts two arguments as shown in the following syntax:

Public Function Substring(ByVal start_Index As Integer, ByVal sub_length As Integer) As String

Here,

  • The ByVal keyword denotes pass-by-value, which is a mechanism of passing arguments to functions.
  • The start_Index is the index from which the substring will be obtained.
  • sub_length denotes the length up to which the String will be copied from the start_Index. This length is measured in terms of the number of characters. The function will return the extracted substring.

The starting index is zero-based, so the first character of the String sits at position 0 rather than position 1.

With the syntax defined, the following examples show the Substring method at work inside a console application.

Examples

Step 1) Create a new console application.

Step 2) Add the following code to it:

Module Module1
    Sub Main()

        Dim st As String = "Guru99"

        Dim subst As String = st.Substring(0, 4)

        Console.WriteLine("The substring is: {0}", subst)

        Console.ReadKey()
    End Sub

End Module

Step 3) Click the Start button from the toolbar to execute the code. You should get the following result:

VB.Net Substring example output

We have used the following code:

VB.Net Substring code example

Explanation of Code:

  1. Creating a module named Module1.
  2. Starting the main sub-procedure.
  3. Defining a string variable named st and assigning the value Guru99 to it.
  4. Defining a string variable named ‘subst’ as a substring of the String ‘st’ from index 0 and a length of 4 characters.
  5. Printing some text and the above substring on the console.
  6. Pausing the console window for a while waiting for the user to take action to close it.
  7. End of the main sub-procedure.
  8. End of the module.

One Argument

What if we pass only one argument to the function? The function will copy all the data in the String that begins from that index. What happens is that the Substring function internally copies all the string data at that index as well as that which follows that index. For example:

Module Module1
    Sub Main()

        Dim st As String = "Guru99"

        Dim subst As String = st.Substring(4)

        Console.WriteLine("The substring is: {0}", subst)


        Console.ReadKey()

    End Sub

End Module

Click the Start button to run the code. It should return the following:

VB.Net Substring with one argument

The Substring function returned 99. We passed the parameter 4 to the function, meaning that it will begin to extract the substring from the character at index 4 to the end of the String. 9 is the character at index 4 of the string Guru99, hence the extraction started there.

Besides trimming from a single index, the Substring method can also target characters in the middle of a String.

Middle Characters

It is also possible for us to get the middle characters of the String in question. In this case, we only have to provide the starting index and the length of the String that we need. In the following example, we are getting a substring of the specified String from index 2 and the String will have a length of 2 characters:

Module Module1
    Sub Main()

        Dim st As String = "Guru99"

        Dim subst As String = st.Substring(2, 2)

        Console.WriteLine("The substring is: {0}", subst)


        Console.ReadKey()

    End Sub

End Module

Click the Start button from the toolbar to run the code. You will get the following result:

VB.Net Substring middle characters

In the above example, the Substring function returned ru. We passed the parameters (2, 2) to the function. The first 2 instructs the function to begin the extraction of the substring from index 2 while the second 2 instructs the function to return a substring with a length of 2 characters only. This means that the extraction of the substring should begin from the element located at index 2 of the string Guru99, which is r. Since the returned substring should only have a length of 2 characters, the extraction will not go past the ‘u’, hence it returned ‘ru.’

One Char

We can use the Substring function to get a single character from a string. In such a case, it is a necessity for you to make an allocation but the character can be accessed directly. This is a bit faster. The following example demonstrates two ways through which we can achieve this:

Module Module1
    Sub Main()

        Dim st As String = "Guru99"

        Dim mid1 As Char = st(1)
        Console.WriteLine(mid1)

        Dim mid2 As String = st.Substring(1, 1)

        Console.WriteLine(mid2)

        Console.ReadKey()

    End Sub

End Module

Click the Start button to run the code. You will get the following result:

VB.Net Substring single character output

We have used the following code:

VB.Net Substring single character code

Explanation of Code:

  1. Creating a module named Module1.
  2. Starting the main sub-procedure.
  3. Defining a string variable named st and assigning the value Guru99 to it.
  4. Defining a string variable named mid1 and getting the character at index 1 of String st. This character will be assigned to the variable mid1.
  5. Printing the above character on the console.
  6. Defining a string variable named mid2 and getting the character at index 1 with a length of 1 from String st. The length of 1 means that it will return the same character at the starting index. The counting begins from the starting index that you specify. This character will be assigned to the variable mid2.
  7. Printing the above character on the console.
  8. Pausing the console window for a while waiting for the user to take action to close it.
  9. End of the main sub-procedure.
  10. End of the module.

Once you are comfortable extracting substrings, it is worth knowing how to handle the errors the method can raise.

Common Substring Errors and How to Avoid Them

The Substring method is strict about the values you pass to it. When an argument falls outside the bounds of the String, VB.Net throws an ArgumentOutOfRangeException and stops the program at run time. Understanding the rules helps you avoid this common mistake.

The method raises the exception in three situations:

  • The start_Index is a negative number.
  • The start_Index is greater than the length of the String.
  • The sum of start_Index and sub_length points beyond the end of the String.

A frequent mistake is using the result of the IndexOf function without checking it first. When IndexOf does not find the character, it returns -1, and passing -1 to Substring triggers the exception. The following code guards against that:

Module Module1
    Sub Main()

        Dim st As String = "Guru99"
        Dim pos As Integer = st.IndexOf("9")

        If pos >= 0 Then
            Dim subst As String = st.Substring(pos)
            Console.WriteLine(subst)
        Else
            Console.WriteLine("Character not found")
        End If

        Console.ReadKey()
    End Sub

End Module

Validating the index before the call keeps your application running smoothly, even when the input String does not contain the character you expect.

Getting a Substring Before or After a Character

A common task is extracting the text that appears before or after a specific character, such as splitting an email address at the @ sign. VB.Net does not provide a dedicated function for this, but you can combine IndexOf with Substring to achieve it.

Text before a character: call IndexOf to locate the character, then pass that index as the length to Substring:

Module Module1
    Sub Main()

        Dim email As String = "guru99@example.com"
        Dim position As Integer = email.IndexOf("@")

        Dim namePart As String = email.Substring(0, position)
        Console.WriteLine(namePart)

        Console.ReadKey()
    End Sub

End Module

The code prints guru99, the portion of the String that sits before the @ sign.

Text after a character: add 1 to the index and let Substring run to the end of the String:

Dim domainPart As String = email.Substring(position + 1)
Console.WriteLine(domainPart)

This returns example.com. When a character appears more than once, use LastIndexOf in place of IndexOf to begin from the final occurrence instead of the first.

Substring vs. Left, Right, and Mid Functions

Visual Basic inherits three legacy string functions from earlier versions: Left, Right, and Mid. They live in the Microsoft.VisualBasic namespace and can feel more familiar to developers coming from classic VB.

  • Left(string, n) returns the first n characters of a String.
  • Right(string, n) returns the last n characters of a String.
  • Mid(string, start, length) returns a portion from a starting position, much like Substring.

The key difference is how they count positions. The Mid function is one-based, so the first character sits at position 1, while the Substring method is zero-based and starts counting at 0. Substring is the standard .NET approach and behaves the same way across every .NET language, so it is the recommended choice for new code. Reserve Left, Right, and Mid for maintaining older Visual Basic projects.

FAQs

Yes. The Substring method is zero-based, so the first character of the String sits at index 0, the second at index 1, and so on. Counting from zero is important when you calculate the starting position.

No. Strings in VB.Net are immutable, so the Substring method never alters the original String. It returns a brand-new String that contains the extracted characters, while the source String keeps its original value unchanged.

Substring extracts one continuous portion of a String using an index and length. Split breaks a String into an array of smaller strings wherever a delimiter, such as a comma or space, appears. Use Split for lists and Substring for slices.

Passing a length of 0 returns an empty String (“”), not Nothing. The call is valid and does not raise an exception, provided the starting index still falls within the bounds of the String.

Substring keeps the portion of the String you specify and discards the rest. The Remove method does the opposite: it deletes the characters starting at a given index and returns the String that remains. They are complementary operations.

Yes. Spaces, tabs, and punctuation each count as one character when the Substring method calculates the starting index and length. Every position in the String, including whitespace, is part of the count, not just the visible letters.

Yes. GitHub Copilot in Visual Studio 2026 turns a plain-English comment, such as extracting the text before a comma, into a working Substring call with IndexOf. Always review the generated indexes to confirm they stay within range.

Yes. Visual Studio 2026 pairs GitHub Copilot with IntelliCode to flag likely out-of-range indexes, suggest correct arguments, and complete Substring calls as you type, helping you prevent an ArgumentOutOfRangeException before you run the program.

Summarize this post with: