Web Development

Normalizing spaces in VB6 strings

The term normalizing spaces refers to removing excess spaces in a string. If you're working with a text processing routine in VB6 that requires you to normalize spaces, check out this code sample and see how easy it is to accomplish this task.

In VB6, the phrase "normalizing spaces" does not refer to fixing abnormal spaces; it refers to removing excess spaces in a string. Some text processing routines (e.g., when working with a database) require the normalization of spaces in order to work properly—particularly when accepting data from the user, because you can never be sure that some extra spaces will not be included.

Normalizing means that you need to remove any trailing or leading strings, which is easy to do with the Trim() function. It also means that you will need to replace any sequence of 2 or more spaces that is present within the string with a single space. This takes a little coding, but it is quite simple with the Instr() and Replace() functions. The following function shows you how:

Private Function NormalizeSpaces(s As String) As String

' Removes all leading and trailing spaces and
' replaces any occurrence of 2 or more spaces
' with a single space.

s = Trim(s)

Do While InStr(s, String(2, " ")) > 0
        s = Replace(s, String(2, " "), " ")
Loop

NormalizeSpaces = s
End Function

Keep this function in your toolbox and you'll be ready whenever you need to normalize strings.

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!

0 comments