Removing some but not all spaces in a string [message #61770] |
Mon, 28 July 2008 13:33 |
wlandsman
Messages: 743 Registered: June 2000
|
Senior Member |
|
|
I'm looking for suggestions for the best way remove the spaces around
"operators" (e.g. <. > , =) in a string but not around other
characters. For example, I want the string
'name = ngc 5548, v <15'
to become
'name=ngc 5548, v<15'
I give a brute force method below which (1) first deals with leading
spaces and then with following spaces (2) breaks apart the string and
then glues it together to remove each space one at a time. Any
ideas on how to improve this?
pro test,st
;remove space around operators in a scalar string, st
st = strcompress(st) ;Ok to compress to a single space
op1 = ' (<|>|=)' ;Operators are <, > and =
n = stregex(st, op1) ;first look for Leading space
while n GT 0 do begin
st = strmid(st,0,n) + strmid(st,n+1) ;piece string together
n = stregex(st,op1) ;Look for another occurrence since
stregex just gives the first
endwhile
op2 = '(<|>|=) ' ;Following space
n = stregex(st, op2)
while n GT 0 do begin
st = strmid(st,0,n+1) + strmid(st,n+2)
n = stregex(st,op2)
endwhile
return
end
|
|
|