TrimEnd. This VB.NET function removes characters from the end of a String. With it we specify an array of Chars we want to remove. It removes those chars if they fall at the end.
Arguments. TrimEnd receives a variable number of arguments. We pass them directly with no special syntax. The TrimStart function works in the same way.
TrimEnd. Here we call TrimEnd on each element in the array. There are three arguments to TrimEnd, which are the punctuation and whitespace characters we want to remove.
Note You can see that the elements in the String array have had certain characters at their ends removed.
Module Module1
Sub Main()
' Input array.
Dim array(1) As String
array(0) = "What's there?"
array(1) = "He's there... "' Use TrimEnd on each String.
For Each element As String In array
Dim trimmed As String = element.TrimEnd("?", ".", " ")
Console.WriteLine("[{0}]", trimmed)
Next
End Sub
End Module[What's there]
[He's there]
TrimStart. TrimStart removes first characters from a String. We specify an array of Chars to be removed. TrimStart then scans the String and removes any characters found.
Tip The function handles not just whitespace but any character value. Specific punctuation characters can be used.
Here We remove 2 Char values from the String: the period and the space. These are part of a Character array.
Note In the String literal, there are three periods and a space. All 4 of those characters are removed from the beginning.
Module Module1
Sub Main()
Dim text As String = "... Dot Net Perls"
Dim array(1) As Char
array(0) = "."
array(1) = " "
text = text.TrimStart(array)
Console.WriteLine("[{0}]", text)
End Sub
End Module[Dot Net Perls]
Array. To trim different characters from the beginning of the String, you can change the array passed to TrimStart. You can trim any character value you wish. The function is case-sensitive.
Optimization. The example shows an inefficient way to use TrimEnd. A new array is created on the heap each time the method is called. With clever programming, this is avoided.
Tip You can create the Char array outside of the loop, or make it a Shared field. Then pass a reference to the existing array to TrimEnd.
Summary. TrimEnd and TrimStart can be helpful in programs that process text in complicated ways. Sometimes, these methods are easier to use than regular expressions.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 22, 2023 (edit).