Retrieve a Portion of a String

Problem

You need to retrieve a portion of a string based on its position and length.

Solution

Use the String.Substring method.

Discussion

The String.Substring method requires two integer parameters, a startIndex and a length. As with all string indexes, startIndex is zero-based (in other words, the first character in the string is designated as character 0).

Dim FullName As String = "Bill Jones"
Dim FirstName As String

' Retrieve the 4-character substring starting at 0.
FirstName = FullName.Substring(0, 4)
' FirstName is now "Bill"

Optionally, you can omit the length parameter to take a substring that continues to the end of the string:

Dim FullName As String = "Bill Jones" Dim LastName As String ' Retrieve the substring ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.