Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

readline to string - strip to seperate variables - how?

Status
Not open for further replies.

marcus76

Technical User
Oct 24, 2007
2
GB
hi,

Please can someone advise how i can take a single string , and seperate out to many strings..problem is, the spaces in between the string caries...i did find some sample script which seems to work, however i need the output all on the same line...see below..appreciate any help

Regards

Marc

Dim Str, Seps(2)
Str = "Tom Dick bvbv d Harry"
Seps(0) = " "
Seps(1) = " "

Dim i, a
a = Tokenize(Str, Seps)
For i=1 to UBound(a)
wscript.echo a(i-1)
next








Function Tokenize(byVal TokenString, byRef TokenSeparators())

Dim NumWords, a()
NumWords = 0

Dim NumSeps
NumSeps = UBound(TokenSeparators)

Do
Dim SepIndex, SepPosition
SepPosition = 0
SepIndex = -1

for i = 0 to NumSeps-1

' Find location of separator in the string

Dim pos
pos = InStr(TokenString, TokenSeparators(i))

' Is the separator present, and is it closest to the beginning of the string?

If pos > 0 and ( (SepPosition = 0) or (pos < SepPosition) ) Then
SepPosition = pos
SepIndex = i
End If

Next

' Did we find any separators?
If SepIndex < 0 Then

' None found - so the token is the remaining string
redim preserve a(NumWords+1)
a(NumWords) = TokenString

Else

' Found a token - pull out the substring
Dim substr
substr = Trim(Left(TokenString, SepPosition-1)) & ","

' Add the token to the list
redim preserve a(NumWords+1)
a(NumWords) = substr

' Cutoff the token we just found
Dim TrimPosition
TrimPosition = SepPosition+Len(TokenSeparators(SepIndex))
TokenString = Trim(Mid(TokenString, TrimPosition))

End If

NumWords = NumWords + 1
loop while (SepIndex >= 0)

Tokenize = a

End Function
 
str = "test1 test2 test5"

str = Trim(str)

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

wscript.echo str2
 
I would use a regular expression....

Code:
str = "test1   test2             test5        "

Dim RegEx : Set RegEx = New RegExp
RegEx.Pattern = "\s{2,}"
RegEx.IgnoreCase = True
RegEx.Global = True

str = RegEx.Replace(str, " ")

WScript.Echo str

--------------------------------------------------------------------------------
dm4ever
My philosophy: K.I.S.S - Keep It Simple Stupid
 
Or this, no trailing space.

Code:
Despace = "test1   test2             test5        "
Dim re
Set re = New RegExp
re.Pattern = "\s+"
re.Global = True
Despace = Trim(re.Replace(Despace, " "))

WScript.Echo Despace



strebor
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top