PDA

View Full Version : Remove multiple spaces between words in a string.


Angelika
06-12-2003, 12:53 PM
Dim str
str = " Leading and trailing spaces... "
str = Trim(str)

'****At this point str = "Leading and trailing spaces..."

While these trimming functions are nice, they don't remove extraneous spaces from between words in the string. For example, if we had the string:

This is a test.

We might want to remove those extra between-word spaces, converting the string to:

This is a test


'****Start by trimming leading/trailing spaces
str = Trim(str)

'Now, while we have 2 consecutive spaces, replace them
'with a single space...
Do While InStr(1, str, " ")
str = Replace(str, " ", " ")
Loop

Or:

Spaces=" "
NumberOfSpaces=5
For i = 1 to NumberOfSpaces
Spaces = Spaces & " "
Do While InStr(1, str, Spaces)
str = Replace(str, " ", " ")
Loop
Next