I used a different method to both left and right trim based on the fact that subroutine parameters are comprised of group of characters separated by spaces, so multiple spaces before the first parameter or after the last one are ignored by them. This way, I get the first character of the first parameter and the last character of the last parameter and use they to delimit the original string. Here it is:
Code: Select all
@echo off
setlocal DisableDelayedExpansion
set "string= qwerty uiop ^carets^ %%percents%% end "
setlocal EnableDelayedExpansion
echo Original: [!string!]
call :TrimSpaces string
echo Trimmed: [!string!]
goto :EOF
:TrimSpaces strVar -- Trim spaces from strVar
if not defined %1 exit /b
setlocal EnableDelayedExpansion
set "var=!%1!"
call :getBounds !var:%%=%%%%!
rem Left trim:
set "var=!var:*%firstChar%=%firstChar%!"
rem Right trim:
if "!var:~-1!" neq " " goto rightTrimmed
set "var=!var:%lastParam% =%lastParam%þ !"
:catNext
for /F "tokens=1,2* delims=þ" %%a in ("!var!") do (
set "var=%%a"
set "mid=%%b"
set "rest=%%c"
)
if defined rest set "var=!var!!mid!þ!rest!"& goto catNext
:rightTrimmed
endlocal & set "%1=%var%"
exit /B
:getBounds
setlocal DisableDelayedExpansion
set "firstParam=%1"
:getlastParam
set "lastParam=%1"
shift
if "%1" neq "" goto getlastParam
endlocal & set "firstChar=%firstParam:~0,1%"& set "lastParam=%lastParam%"
exit /B
This first version of this code have the same common problems with special characters, that may or may not be solved in the usual ways.
EDIT: I slightly modified the code to process as delimiter the entire last parameter instead of just its last character; this avoid to process several words that may have the same last character than the last word. If the last word is unique, right trim consist in two steps: get the last parameter and trim the spaces after it. If there are several words equal to the last one, then a loop is required to process each one and trim spaces after the last one. Left trim is always a two step process: get the first character and trim the spaces before it.
Antonio