Wednesday, May 21, 2008

Working with String.Trim() Function

Level: Beginner

This article discusses the main functionality of String.Trim() function and also explains how to trim other characters along with White Spaces.

As we all know that Trim() function is used to remove the Spaces from Left and Right of a String. E.g.:

Dim SomeText As String
SomeText = " Text with some spaces on Left and Right "
SomeText = SomeText.Trim()

Output will be

Text with some spaces on Left and Right

But Trim() actually removes the White Space Characters (White Space = Space, Tab, Enter, etc.)


Dim SomeText As String
SomeText = vbTab & vbCrLf " Text with some spaces on Left and Right " & vbTab & vbCrLf
SomeText = SomeText.Trim()

Still output will be the same.

Sometimes we also require to remove the other characters along with White Spaces.

For Example: We have taken a File Name from some other string and it contains Tab, Enter or Spaces in its Start and/or End plus the File Name will be enclosed in Apostrophe or Quotation (' or "). So we want to remove the White Spaces, Apostrophe/Quotation from Start/End. In this way we will get the plain file name only which we can use for other purposes. To check I am creating a file name here as,

FileName = vbTab & vbCrLf & "'C:\ABC\Def.txt'    "

As you can see I have added the Tab, Enter and Apostrophe in the start. Now to Trim it properly we will use the following code,

FileName = FileName.Trim() ' first remove the White Spaces
FileName = FileName.Trim("'"c, """"c) ' now remove the Apostrophe/Quotation

As you can see we have used a simple technique, i.e.

  • first we have removed the White Space Characters by calling the simple Trim() function
  • then we have used its overloaded definition i.e. Trim(ParamArray CharArray() as Char)

No comments: