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
set "string= qwerty uiop ^carets^ %%percents%% end "
echo Original: [!string!]
call :TrimSpaces string
echo Trimmed: [!string!]
:TrimSpaces strVar -- Trim spaces from strVar
if not defined %1 exit /b
call :getBounds !var:%%=%%%%!
rem Left trim:
rem Right trim:
if "!var:~-1!" neq " " goto rightTrimmed
set "var=!var:%lastParam% =%lastParam%þ !"
for /F "tokens=1,2* delims=þ" %%a in ("!var!") do (
if defined rest set "var=!var!!mid!þ!rest!"& goto catNext
endlocal & set "%1=%var%"
if "%1" neq "" goto getlastParam
endlocal & set "firstChar=%firstParam:~0,1%"& set "lastParam=%lastParam%"
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.