TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< 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.

Console
VB.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.IsNullOrEmpty

Version 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.

Exception
VB.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.

IndexOf

Part 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, After
A 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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


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