Home
VB.NET
String LTrim and RTrim Functions
This page was last reviewed on Sep 14, 2022.
Dot Net Perls
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.
Similar to TrimStart, and TrimEnd, these 2 VB.NET functions are familiar and may be useful still. They call into TrimStart and TrimEnd.
String TrimEnd, TrimStart
String Trim
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.
Module Module1 Sub Main() Dim value1 As String = " abc" Dim value2 As String = LTrim(value1) Console.WriteLine("[{0}]", value2) End Sub End Module
[abc]
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.
Detail 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.
Module Module1 Sub Main() Dim value1 As String = "xyz " Dim value2 As String = RTrim(value1) Console.WriteLine("[{0}]", value2) End Sub End Module
[xyz]
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.
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.
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 Sep 14, 2022 (grammar).
Home
Changes
© 2007-2024 Sam Allen.