Trimming whitespace

Previous topic - Next topic

FutureCow

On reflection, this could probably have been done with a 1 line inline call to whatever the C string trimming functions are (does someone want to provide it? - my C's very sketchy nowadays and I couldn't be bothered looking up a C manual to find it.)

However, I've already written the code now, so here's my GLBasic method to trim both leading and trailing whitepace from a string.

Code (glbasic) Select

LOCAL TempChar$, StringToTrim$
LOCAL CharLoop, FirstNonSpace, LastNonSpace, StringLength

StringToTrim$="     This is my test string       "
LastNonSpace=0
FirstNonSpace=-1
StringLength=LEN(StringToTrim$)
FOR CharLoop = 0 TO StringLength
TempChar$ = MID$(StringToTrim$,CharLoop,1)
IF ASC(TempChar$) = 0 // End of string character read
BREAK
ENDIF

IF TempChar$ <> " " // Current character is a non-space
IF FirstNonSpace = -1 // we only want to set this once
FirstNonSpace = CharLoop // when we read the first non " " character
ENDIF
LastNonSpace=CharLoop // Constantly update the last non " " character when a non " " is read

ENDIF
NEXT
StringToTrim$ = MID$(StringToTrim$,FirstNonSpace,LastNonSpace+1-FirstNonSpace)


Quentin

#1
here's another version

Code (glbasic) Select

LOADFONT "arial.png", 0

a$ = "    a string with leading and trailing spaces      "
b$ = trim$(a$)

PRINT a$, 0, 0
PRINT b$, 0, 20
SHOWSCREEN
KEYWAIT


// ------------------------------------------------------------- //
// ---  TRIM$  ---
// ------------------------------------------------------------- //
FUNCTION trim$: pstring$

LOCAL lv_len%
LOCAL lv_start%, lv_end%

lv_len = LEN(pstring$)
lv_end = lv_len - 1

WHILE MID$(pstring$, lv_start, 1) = " "
INC lv_start
WEND

WHILE MID$(pstring$, lv_end, 1) = " "
DEC lv_end
WEND

RETURN MID$(pstring$, lv_start, lv_end - lv_start)

ENDFUNCTION // TRIM$

MrTAToad

How about :

Code (glbasic) Select
a$="     This is a test      "

a$=trimLeft$(a$)
a$=trimRight$(a$)
DEBUG ">>>"+a$+"<<<"
END

FUNCTION trimLeft$:text$
WHILE MID$(text$,0,1)=" "
text$=MID$(text$,1)
WEND
RETURN text$
ENDFUNCTION

FUNCTION trimRight$:text$
WHILE MID$(text$,LEN(text$)-1,1)=" "
text$=MID$(text$,0,LEN(text$)-1)
WEND
RETURN text$
ENDFUNCTION