<< Back to VBNET
VB.NET Substring Examples
Use the Substring Function to get parts of strings. Review the arguments to Substring.Substring. This function gets parts of a String. It receives 2 arguments. These indicate the start index, and the length, of the character data.
A new String. Substring() returns a new String instance containing the range of characters. It throws Exceptions on invalid arguments.
First example. Here we use Substring to get the first several characters of an input string. It takes the first 3 chars from the source string and copies them into a new string.
Result: A new String is returned. We can manipulate this substring more easily in other program parts.
Argument 1: The first argument to Substring() is the start index in the source string. So 0 means start at the first char.
Argument 2: This is the count of chars—when the second argument is 3, this means continue for 3 chars. The result is a 3-char string.
VB.NET program that uses Substring
Module Module1
Sub Main()
Dim literal As String = "523-1242"
' Take the first 3 characters and put them in a new string.
Dim substring As String = literal.Substring(0, 3)
Console.WriteLine("SUBSTRING: {0}", substring)
End Sub
End Module
Output
SUBSTRING: 523
One argument. Next we call the Substring Function with a single argument. Substring will internally copy all the string data at that index and following that index.
Tip: When we use Substring with one argument, the return value contains all the character data starting at, and following, that index.
VB.NET program that uses Substring with one argument
Module Module1
Sub Main()
' Use this string literal.
' ... Next, use the Substring method with one parameter.
Dim literal As String = "CatDogFence"
Dim substring As String = literal.Substring(6)
Console.WriteLine("Substring: {0}", substring)
End Sub
End Module
Output
Substring: Fence
Middle characters. We can take the middle chars in a string. The Substring method can be used with a start index and a length that is greater than zero to acquire the middle characters.
Info: We take characters 4 through 7, and then place them in a Substring and print the result with Console.WriteLine.
ConsoleVB.NET program that uses Substring for middle characters
Module Module1
Sub Main()
' Use the string literal.
' ... Then use Substring to take a middle substring.
Dim literal As String = "CatDogFence"
Dim substring As String = literal.Substring(3, 3)
Console.WriteLine("Result: {0}", substring)
End Sub
End Module
Output
Result: Dog
Relative indexes. We can base the arguments to Substring on the result of the Length property of the original string minus some constant.
Tip: This allows some functions to handle more input strings, reducing the amount of special-casing you must do.
Tip 2: This is a way you can base the length of the Substring on the length of the original string, providing more flexible code.
VB.NET program that uses Substring with Length arguments
Module Module1
Sub Main()
' Use Length to handle relative indexes.
Dim literal As String = "CatDogFence"
Dim substring As String =
literal.Substring(3, literal.Length - 5 - 3)
Console.WriteLine("Middle string: {0}", substring)
End Sub
End Module
Output
Middle string: Dog
Null Substring. If our String may be null, we should test it with a function like String.IsNullOrEmpty before calling Substring. Consider this program—it causes an exception.
String.IsNullOrEmptyVersion 1: Here we have code that does not crash—it tests the String for Nothing, and the code inside the If-statement does not run.
Version 2: This code causes the NullReferenceException. We cannot take a Substring of a null (Nothing) String.
ExceptionVB.NET program that causes NullReferenceException
Module Module1
Sub Main()
Dim data As String = Nothing
' Version 1: this is safe.
If Not String.IsNullOrEmpty(data) Then
Console.WriteLine(data.Substring(1))
End If
' Version 2: this will fail.
Dim result = data.Substring(1)
End Sub
End Module
Output
Unhandled Exception: System.NullReferenceException:
Object reference not set to an instance of an object.
IndexOf and Substring. These functions are made to be used together. Suppose we have a label inside a string, and we want to get the string part following that label.
Part 1: We use IndexOf to search for the separator that follows the label. This returns the index of the separator.
IndexOfPart 2: If the separator was found, its index is a positive number. We get the Substring at this index, adding in the separator's length.
Tip: It is important to add in the length of the separator string—otherwise, we will have the separator at the start of our substring.
VB.NET program that uses IndexOf and Substring
Module Module1
Sub Main()
Dim data As String = "Item: 123 X"
' Part 1: get the index of a separator with IndexOf.
Dim separator As String = ": "
Dim separatorIndex = data.IndexOf(separator)
' Part 2: see if separator exists.
' ... Get the following part with Substring.
If separatorIndex >= 0 Then
Dim value As String = data.Substring(separatorIndex + separator.Length)
Console.WriteLine("RESULT: {0}", value)
End If
End Sub
End Module
Output
RESULT: 123 X
First words. To get the first words from a String, we can count word separators (like spaces) in a For-loop. Then we take a Substring to get just those words.
Here: The FirstWords method counts spaces in the input string. Once the required number is reached, a Substring is returned.
Words: The correct number of words are present in the output. There are 5 and 3 words in the result strings.
VB.NET program that gets first words from string
Module Module1
Public Function FirstWords(input As String,
count As Integer) As String
Dim words = count
For i As Integer = 0 To input.Length - 1
' Decrement word count when we reach a space.
If input(i) = " " Then
words -= 1
End If
' When no words remaining, return a substring to this point.
If words = 0 Then
Return input.Substring(0, i)
End If
Next
Return ""
End Function
Sub Main()
' Test our FirstWords method.
Dim example1 =
"This is an example summary that we are using."
Console.WriteLine(FirstWords(example1, 5))
Dim example2 =
"How many words are in this sentence?"
Console.WriteLine(FirstWords(example2, 3))
End Sub
End Module
Output
This is an example summary
How many words
Right. In some programs a Function that calls Substring in a special way may be helpful. Here we see a Right method. It returns a substring located on the right side of a string.
Arguments: The first argument is the string to take the substring from. And the second is the length of the substring part.
VB.NET program that uses substring in Right method
Module Module1
Function Right(value As String, length As Integer) As String
' Get rightmost characters of specified length.
Return value.Substring(value.Length - length)
End Function
Sub Main()
' Test the Right function.
Dim phrase1 As String = "cat and dog"
Dim result1 As String = Right(phrase1, 3)
Console.WriteLine(result1)
End Sub
End Module
Output
dog
One Char. We can get a one-char string with the Substring function. But for this special case, we can just access a Char from the String, which is much faster. No allocation is needed.
VB.NET program that uses one-char substrings
Module Module1
Sub Main()
Dim value As String = "CAT"
' Get a one-char substring as a Char.
' ... This is faster.
Dim middle1 As Char = value(1)
Console.WriteLine(middle1)
' Get a one-char substring as a String.
Dim middle2 As String = value.Substring(1, 1)
Console.WriteLine(middle2)
End Sub
End Module
Output
A
A
Benchmark, one char. Avoiding Substring when possible is probably the most important optimization here. Substring() is a String function that does significant work.
Version 1: Here we access the last Char in a string. We test the Char against the character literal "m."
Version 2: In this version of the code we call Substring to get a 1-char string containing the last character.
Result: It is many times faster to access the Char, and test it directly, without calling Substring.
VB.NET program that times one-char Substring
Module Module1
Sub Main()
Dim data As String = "arm"
Dim m As Integer = 10000000
' Version 1: test last char of String.
Dim s1 As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To m - 1
Dim lastChar = data(data.Length - 1)
If lastChar <> "m"c Then
Return
End If
Next
s1.Stop()
' Version 2: test last 1-char Substring of String.
Dim s2 As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To m - 1
Dim lastCharString = data.Substring(data.Length - 1)
If lastCharString <> "m" Then
Return
End If
Next
s2.Stop()
Dim u As Integer = 1000000
Console.WriteLine(((s1.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns"))
Console.WriteLine(((s2.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns"))
End Sub
End Module
Output
0.88 ns One-char access
21.35 ns One-char substring
String copying. Let us consider Substring's internal implementation. When we call the Substring function, a new string copy is made. A reference to this string data is returned.
Note: When we assign to the result of the Substring function, we are performing a bitwise copy of only that reference.
Also: In some algorithms, using strings that already exist is much faster than creating substrings.
Mid. VB.NET has special support for the Mid built-in statement. With Mid, we can get a substring or assign to a substring based on start and length arguments.
Mid Statement
Between substrings. Sometimes a simple parser may need to find substrings between, before and after other ones. Some functions can be used to implement this useful logic.
Between, Before, AfterA review. Substring copies a series of characters from a source string into a new string that is allocated upon the managed heap. It is called with 1 or 2 arguments.
Related Links:
- VB.NET Nullable
- VB.NET Convert Char Array to String
- VB.NET Object Array
- VB.NET File.ReadAllText, Get String From File
- VB.NET Compress File: GZipStream Example
- VB.NET Console.WriteLine (Print)
- VB.NET File.ReadLines Example
- VB.NET AddressOf Operator
- VB.NET Recursion Example
- VB.NET Recursive File Directory Function
- VB.NET Regex, Read and Match File Lines
- VB.NET Regex.Matches Quote Example
- VB.NET Regex.Matches: For Each Match, Capture
- VB.NET Convert String, Byte Array
- VB.NET File Size: FileInfo Example
- VB.NET File Handling
- VB.NET String.Format Examples: String and Integer
- VB.NET SyncLock Statement
- VB.NET TextInfo Examples
- VB.NET Array.Copy Example
- VB.NET HtmlEncode, HtmlDecode Examples
- VB.NET HtmlTextWriter Example
- VB.NET Stack Type
- VB.NET Func, Action and Predicate Examples
- VB.NET Function Examples
- VB.NET GoTo Example: Labels, Nested Loops
- VB.NET Array.Find Function, FindAll
- VB.NET HttpClient Example: System.Net.Http
- VB.NET DataColumn Class
- VB.NET DataGridView
- VB.NET DataSet Examples
- VB.NET DataTable Select Function
- VB.NET DataTable Examples
- VB.NET Attribute Examples
- VB.NET OpenFileDialog Example
- VB.NET Benchmark
- VB.NET BinaryReader Example
- VB.NET BinarySearch List
- VB.NET BinaryWriter Example
- VB.NET Regex.Replace Function
- VB.NET Regex.Split Examples
- VB.NET Regex.Match Examples: Regular Expressions
- VB.NET Convert ArrayList to Array
- VB.NET Array Examples, String Arrays
- VB.NET ArrayList Examples
- VB.NET Boolean, True, False and Not (Return True)
- VB.NET Nothing, IsNothing (Null)
- VB.NET Directive Examples: Const, If and Region
- VB.NET Do Until Loops
- VB.NET Do While Loop Examples (While)
- VB.NET Array.Resize Subroutine
- VB.NET Chr Function: Get Char From Integer
- VB.NET Class Examples
- VB.NET IndexOf Function
- VB.NET Insert String
- VB.NET Interface Examples (Implements)
- VB.NET 2D, 3D and Jagged Array Examples
- VB.NET Enum.Parse, TryParse: Convert String to Enum
- VB.NET Remove HTML Tags
- VB.NET Remove String
- VB.NET Event Example: AddHandler, RaiseEvent
- VB.NET Excel Interop Example
- VB.NET StartsWith and EndsWith String Functions
- VB.NET Initialize List
- VB.NET Number Examples
- VB.NET Optional String, Integer: Named Arguments
- VB.NET Replace String Examples
- VB.NET Exception Handling: Try, Catch and Finally
- VB.NET Enum Examples
- VB.NET Enumerable.Range, Repeat and Empty
- VB.NET Dictionary Examples
- VB.NET Double Type
- VB.NET LSet and RSet Functions
- VB.NET LTrim and RTrim Functions
- VB.NET Alphanumeric Sorting
- VB.NET PadLeft and PadRight
- VB.NET String.Concat Examples
- VB.NET String
- VB.NET Math.Abs: Absolute Value
- VB.NET Array.IndexOf, LastIndexOf
- VB.NET Remove Duplicate Chars
- VB.NET If Then, ElseIf, Else Examples
- VB.NET ParamArray (Use varargs Functions)
- VB.NET Integer.Parse: Convert String to Integer
- VB.NET ThreadPool
- VB.NET Process Examples (Process.Start)
- VB.NET TimeZone Example
- VB.NET Path Examples
- VB.NET ToArray Extension Example
- VB.NET ToCharArray Function
- VB.NET Stopwatch Example
- VB.NET Button Example
- VB.NET StreamReader ReadToEnd Function
- VB.NET ByVal Versus ByRef Example
- VB.NET StreamReader Example
- VB.NET StreamWriter Example
- VB.NET String.Compare Examples
- VB.NET Cast: TryCast, DirectCast Examples
- VB.NET String Constructor (New String)
- VB.NET String.Copy and CopyTo
- VB.NET Math.Ceiling and Floor: Double Examples
- VB.NET Math.Max and Math.Min
- VB.NET WebClient: DownloadData, Headers
- VB.NET Math.Round Example
- VB.NET Math.Truncate Method, Cast Double to Integer
- VB.NET Reverse String
- VB.NET Structure Examples
- VB.NET Sub Examples
- VB.NET Substring Examples
- VB.NET Convert Dictionary to List
- VB.NET Convert List and Array
- VB.NET Convert List to String
- VB.NET Convert Miles to Kilometers
- VB.NET Property Examples (Get, Set)
- VB.NET Remove Punctuation From String
- VB.NET Queue Examples
- VB.NET Const Values
- VB.NET Remove Duplicates From List
- VB.NET IComparable Example
- VB.NET ReDim Keyword (Array.Resize)
- VB.NET Contains Example
- VB.NET IEnumerable Examples
- VB.NET IsNot and Is Operators
- VB.NET String.IsNullOrEmpty, IsNullOrWhiteSpace
- VB.NET ROT13 Encode Function
- VB.NET StringBuilder Examples
- VB.NET Image Type
- VB.NET Val, Asc and AscW Functions
- VB.NET String.Empty Example
- VB.NET String.Equals Function
- VB.NET VarType Function (VariantType Enum)
- VB.NET With Statement
- VB.NET WithEvents: Handles and RaiseEvent
- VB.NET String Length Example
- VB.NET ToList Extension Example
- VB.NET ToLower and ToUpper Examples
- VB.NET TextBox Example
- VB.NET ToString Overrides Example
- VB.NET ToTitleCase Function
- VB.NET Convert String Array to String
- VB.NET Iterator Example: Yield Keyword
- VB.NET Mid Statement
- VB.NET Mod Operator (Odd, Even Numbers)
- VB.NET Convert String to Integer
- VB.NET Module Example: Shared Data
- VB.NET Integer
- VB.NET Keywords
- VB.NET Lambda Expressions
- VB.NET LastIndexOf Function
- VB.NET String Join Examples
- VB.NET Multiple Return Values
- VB.NET MustInherit Class: Shadows and Overloads
- VB.NET Namespace Example
- VB.NET KeyValuePair Examples
- VB.NET Environment.NewLine: vbCrLf
- VB.NET Levenshtein Distance Algorithm
- VB.NET Shared Function
- VB.NET Shell Function: Start EXE Program
- VB.NET Sleep Subroutine (Pause)
- VB.NET Sort Dictionary
- VB.NET Exit Statements
- VB.NET LINQ Examples
- VB.NET List Examples
- VB.NET Extension Method
- VB.NET Select Case Examples
- VB.NET MessageBox.Show Examples
- VB.NET Timer Examples
- VB.NET TimeSpan Examples
- VB.NET BackgroundWorker
- VB.NET String Between, Before and After Functions
- VB.NET CStr Function
- VB.NET DataRow Field Extension
- VB.NET DataRow Examples
- VB.NET DateTime Format
- VB.NET Char Examples
- VB.NET DateTime.Now Property (Today)
- VB.NET DateTime.Parse: Convert String to DateTime
- VB.NET DateTime Examples
- VB.NET Decimal Type
- VB.NET HashSet Example
- VB.NET Hashtable Type
- VB.NET Fibonacci Sequence
- VB.NET XmlWriter, Create XML File
- VB.NET File.Copy: Examples, Overwrite
- VB.NET File.Exists: Get Boolean
- VB.NET Path.GetExtension: File Extension
- VB.NET Tuple Examples
- VB.NET Trim Function
- VB.NET TrimEnd and TrimStart Examples
- VB.NET Word Count Function
- VB.NET Word Interop Example
- VB.NET For Loop Examples (For Each)
- VB.NET XElement Example
- VB.NET Truncate String
- VB.NET Sort Number Strings
- VB.NET Sort Examples: Arrays and Lists
- VB.NET SortedList
- VB.NET SortedSet Examples
- VB.NET Split String Examples
- VB.NET Uppercase First Letter
- VB.NET XmlReader, Parse XML File
- VB.NET ZipFile Example
- VB.NET Array.Reverse Example
- VB.NET Random Lowercase Letter
- VB.NET Byte Array: Memory Usage
- VB.NET Byte and Sbyte Types
- VB.NET Char Array
- VB.NET Random String
- VB.NET Random Numbers
- VB.NET Async, Await Example: Task Start and Wait
- VB.NET Choose Function (Get Argument at Index)
- VB.NET Sort by File Size
- VB.NET Sort List (Lambda That Calls CompareTo)
- VB.NET List Find and Exists Examples
- VB.NET Math.Sqrt Function
- VB.NET Loop Over String: For, For Each
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf