How to VB.NET String.substring()

The Substring method in the VB.NET String Class allows you to obtain a portion of a string by creating a new string that represents a substring of the original string. This substring starts at a specified index position and can extend up to a given length.

When using the Substring method, you provide two parameters: the starting index and the length. The starting index indicates the position within the original string where the desired substring begins. The length parameter specifies the number of characters to include in the substring.

The Substring method has two overloads:

Substring(startIndex As Integer) 'This overload extracts the substring starting from the specified startIndex until the end of the string.
Substring(startIndex As Integer, length As Integer) 'This overload extracts the substring starting from the specified startIndex and with the specified length.

Examples | Usage of the Substring method

Extracting a substring from a specific index until the end of the string

Dim input As String = "Hello, World!" Dim startIndex As Integer = 7 ' Index where the substring starts Dim result As String = input.Substring(startIndex) Console.WriteLine("Original string: " & input) Console.WriteLine("Substring from index " & startIndex & " until the end: " & result)
Output:
Original string: Hello, World! Substring from index 7 until the end: World!

In this example, we have a string named "input" and an integer variable "startIndex" set to 7. We call the Substring method on the "input" string, passing the "startIndex" as the argument. This will extract the substring starting from index 7 until the end of the string. The resulting substring is stored in the "result" variable and displayed.

Extracting a substring with a specific length

Dim input As String = "Hello, World!" Dim startIndex As Integer = 7 ' Index where the substring starts Dim length As Integer = 5 ' Length of the substring Dim result As String = input.Substring(startIndex, length) Console.WriteLine("Original string: " & input) Console.WriteLine("Substring from index " & startIndex & " with length " & length & ": " & result)
Output:
Original string: Hello, World! Substring from index 7 with length 5: World

In this example, we have a string named "input" and two integer variables: "startIndex" set to 7 and "length" set to 5. We call the Substring method on the "input" string, passing both the "startIndex" and "length" as arguments. This will extract a substring starting from index 7 with a length of 5 characters. The resulting substring is stored in the "result" variable and displayed.

Conclusion

The Substring method provides flexibility in extracting substrings from a string based on specific requirements, allowing you to manipulate and process string data effectively in your VB.NET applications.