Error in "String Trimming Left and Right"

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
ITI
Posts: 1
Joined: 15 Apr 2012 17:20
Location: Edmonton Ab, Canada
Contact:

Error in "String Trimming Left and Right"

#1 Post by ITI » 15 Apr 2012 18:04

I have discovered an error in: "String Trimming Left and Right - :trim, :trimLeft, :trimRight" which you have so kindly posted on this page http://www.dostips.com/DtCodeFunctions.php

The "trim" and "trimRight" work correctly if and only if the variable passed in is the same as the one used in your function:

Code: Select all

set s=  trim or trimRight this line   &call:trimRight s&echo."!s!"

Your Function:

Code: Select all

:trimRight -- trim trailing spaces
:          -- %~1: variable reference, string to be trimmed
SETLOCAL
:trimLeft_LOOP
set s=!%~1!
if "%s:~-1%"==" " set s=%s:~0,-1%&goto:trimLeft_LOOP
(ENDLOCAL & REM.-- RETURN VALUES
    IF "%~1" NEQ "" SET %~1=%s%
)
GOTO:EOF

Above works correctly, however, entering the following will result in an endless loop.

Code: Select all

set thisVar=    trim or trimRight this line       &call:trimRight thisVar&echo."!thisVar!"
:: OR
set thisVar=    trim or trimRight this line       &call:trim thisVar&echo."!thisVar!"

In the function, set s=!%~1! must be assigned before :trimLeft_LOOP
The Modified Function:

Code: Select all

:trimRight -- trim trailing spaces
:          -- %~1: variable reference, string to be trimmed
SETLOCAL
set s=!%~1!  << Moved to here, before the loop label.
:trimLeft_LOOP
if "%s:~-1%"==" " set s=%s:~0,-1%&goto:trimLeft_LOOP
(ENDLOCAL & REM.-- RETURN VALUES
    IF "%~1" NEQ "" SET %~1=%s%
)
GOTO:EOF


The function will now work as I'm sure you originally intended.
Glen

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: Error in "String Trimming Left and Right"

#2 Post by Ed Dyreen » 15 Apr 2012 23:35

'
That's a bug alright, did you contact the site admin with a private message ?

admin
Site Admin
Posts: 129
Joined: 31 Dec 1969 18:00
Location: US

Re: Error in "String Trimming Left and Right"

#3 Post by admin » 18 Apr 2012 19:26

Thank you ITI for pointing this out.
It is now fixed.
:D

Post Reply