!str:~1,%len%! never expands properly. If I replace the variable with a hard-coded value, the function works just fine, but I would like to have it to ensure I do not cut off my string. Any help is appreciated
Code: Select all
@echo off
set "string1= string1"
set "string2= string2 "
set "string3= string3"
echo "%string1%"
echo "%string2%"
echo "%string3%"
call :lTrim string1 "%string1%" " "
call :lTrim string2 "%string2%" " "
call :lTrim string3 "%string3%" " "
echo "%string1%"
echo "%string2%"
echo "%string3%"
pause
goto :eof
:lTrim
rem Trims a character from the left side of a string.
rem -Requires length function
rem
rem Syntax: rTrim [rVar] "string" "character"
setlocal enabledelayedexpansion
set "str=%~2"
set "char=%~3"
call :length len "%str%"
for /l %%a in (0,1,%len%) do if "!str:~0,1!"=="!char!" set "str=!str:~1,%len%!"
endlocal & if not "%~1"=="" set "%~1=%str%" & exit /b
:length
rem Returns the length of a string.
rem
rem Syntax: length [rVar] "string"
setlocal enabledelayedexpansion
set "str=%~2"
set "len=0"
set "count=0"
:length_loop
if "!str:~%len%,1!"=="" (
endlocal & if not "%~1"=="" set %~1=%len% & exit /b
) else set /a len=len+1
goto :length_loop
Output (nothing I have tried except hard-coding the %len% variable has changed this)
Code: Select all
" string1"
" string2 "
" string3"
"str:~1,17 "
"str:~1,14 "
"str:~1,21 "
Press any key to continue . . .
Also: the lTrim algorithm in the library just doesn't seem to work for me(?) which is why I am creating my own. I'll test it again just to be sure, but for now I would still like to have this function working.