Dealing with Whitespace in Visual Basic Strings

Today I’ve been continuing with a Visual Basic project at work, and I ran into an issue whereby after I convert an Integer to a String using the Str(strMyString) command, the resulting string was given a leading space. This is a known outcome from the use of the Str command however I needed to find a solution.

I today discovered the LTrim and RTrim commands.

Using the LTrim command, declared as a second string you are able to produce the following:

Dim strMyString As String
Dim strMyStringLeft As String

strMyString = "     Some Text     "
strMyStringLeft = LTrim (strMyString)

As you can see, my string starts life as “    Some Text    “. Once passed through the LTrim grinder, the value of strMyStringLeft will be “Some Text    “. As you can guess, passing strMyStringLeft through another variable will remove the leading whitespace as follows:

Dim strMyString As String
Dim strMyStringLeft As String
Dim strMyStringRight As String

strMyString = "    Some Text    "
strMyStringLeft = LTrim(strMyString)
strMyStringRight = RTrim(strMyStringLeft)

The value of strMyStringRight would now be “Some Text”. This is achieved because we used strMyStringLeft as the input for strMyStringRight meaning that the leading space was already removed.

Although my way of doing this is probably a little longer than some VB guru will do by combing the statements, it’s easy for a beginner like me to interpret the code.

richardjgreen

Richard works as a Cloud Consultant for Fordway Solution where his primary focus is to help customers understand, adopt and develop with Microsoft Azure, Office 365 and System Center. Richard Green is an IT Pro with over 15 years' of experience in all things Microsoft including System Center and Office 365. He has previously worked as a System Center consultant and as an internal solutions architect across many verticals. Outside of work, he loves motorbikes and is part of the orange army, marshaling for NGRRC, British Superbikes and MotoGP. He is also an Assistant Cub Scout Leader.