VB.NET LTrim and RTrim FunctionsUse the LTrim and RTrim Functions, which remove spaces from the left and right.
LTrim, RTrim. The L stands for Left—the left trim method removes spaces from the left of a String. RTrim removes from the right side of String data.
Simlilar to TrimStart, and TrimEnd, these 2 VB.NET functions are familiar and may be useful still. They call into TrimStart and TrimEnd.
TrimEnd, TrimStart
LTrim. In this example, we declare a String literal with 3 spaces at its start. Then, we pass the variable that points to that String literal to the LTrim function.
Result The string value returned has no leading spaces on it. The spaces have been entirely removed.
VB.NET program that uses LTrim function
Module Module1 Sub Main() Dim value1 As String = " abc" Dim value2 As String = LTrim(value1) Console.WriteLine("[{0}]", value2) End Sub End Module
RTrim. A String literal with several trailing spaces is declared and the value1 variable points to it. When this variable is passed to RTrim, another String is returned.
Output We can see that there are no trailing spaces remaining on the right side of the string value.
Note The original String literal is unchanged, but changes are made to another copy which is displayed.
VB.NET program that calls RTrim
Module Module1 Sub Main() Dim value1 As String = "xyz " Dim value2 As String = RTrim(value1) Console.WriteLine("[{0}]", value2) End Sub End Module
How is the LTrim function implemented? To investigate, I opened the Microsoft.VisualBasic.dll file with IL Disassembler. I found that, internally, LTrim calls TrimStart.
Info It would be more efficient to simply call TrimStart yourself. This is possible without too much trouble.
TrimEnd, TrimStart
Internally, RTrim simply calls TrimEnd on the String type. TrimEnd is a form of Trim that only acts on the trailing (right-side) characters.
Summary. We looked at the LTrim function (and its implementation) in VB.NET. This function may be convenient and familiar—but it simply invokes TrimStart.
© 2007-2021 sam allen. see site info on the changelog