Trim. This VB.NET function removes leading and trailing whitespace. String data often has leading or trailing whitespace characters—newlines, spaces or tabs.
Characters like spaces at the end or start are usually not needed. With Trim we strip these characters in a declarative way. Other program logic may become simpler.
This code references a string literal that contains leading spaces and a trailing space. Next the Trim Function is invoked, and a new string is allocated on the managed heap.
Tip The string returned by the Trim Function does not contain the leading spaces or trailing space.
Next To demonstrate, we print out the resulting value with square brackets denoting its first and last character positions.
Module Module1
Sub Main()
' Input string.
Dim value As String = " This is an example string. "' Invoke Trim function.
value = value.Trim()
' Write output.
Console.Write("[")
Console.Write(value)
Console.WriteLine("]")
End Sub
End Module[This is an example string.]
File lines. Text files may have unnecessary spaces or tab characters. If you read in a file line-by-line you can then trim these lines and process them with simpler logic.
Imports System.IO
Module Module1
Sub Main()
' Read in the lines of a file.
For Each line As String In File.ReadAllLines("data.txt")
' The existing line.
Console.WriteLine("[{0}]", line)
' Trimmed line.
Dim trimmed As String = line.Trim()
Console.WriteLine("[{0}]", trimmed)
Next
End Sub
End Module[ Something]
[Something]
[Example ]
[Example]
[ Another]
[Another]
Dictionary. A Dictionary can store string keys and reference data objects as values. It is a good idea to trim input before passing it to a Dictionary lookup method.
Tip This ensures that whitespace, which is typically not meaningful in this context, will not disrupt accurate lookups.
A summary. The Trim Function clears excess leading and trailing whitespace characters from string data. With Trim we more easily accept input from users and files.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 22, 2023 (edit).