I'm trying to get a String of an users input and then let the Text scroll.
What I have so far:
@echo off
setlocal
set /p myString=String:
cls
call :StringLenght result myString
:ECHO
set /a result=%result%-1
set myString=%mystring:~%result%%
echo %myString%
ping -n 2 localhost>nul
cls
:StringLenght <resultVar> <stringVar>
(
setlocal EnableDelayedExpansion
set "s=!%~2!#"
set "len=0"
for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if "!s:~%%P,1!" NEQ "" (
set /a "len+=%%P"
set "s=!s:~%%P!"
)
)
)
(
endlocal
set "%~1=%len%"
goto ECHO
)
Now at this Point it doesn't works:
set myString=%mystring:~%result%%
I can't get the String out of a variable when I'm in a variable %% (Sounds weird but I think you can imagine what I mean).
You need delayed expansion for this to work.
Here is the concept:
@echo off
setlocal EnableDelayedExpansion
set "mystring=mousetail"
set result=5
echo %mystring%
echo !mystring:~%result%!
Should be easy to implement into your code.
An alternative without delayed expansion is to use the call
command like this:
@echo off
set "myString=something"
set "result=4"
echo %myString%
call echo %%myString:~%result%%%
What happens is that the expansion of Result
is done immediately but the expansion of myString
is carried out to the new cmd
instance opened by call
:
- firstly, the
%%
after echo
is replaced by a single %
;
- secondly,
%result%
is expanded, that is, replaced by its value 4
;
- thirdly, the last
%%
is replaced by a single %
;
- and lastly, the command line
echo %myString:~4%
is passed over to the new cmd
instance opened by call
, thus thing
is displayed;
Notice, that this only works in a batch file but not in command prompt (cmd
) directly.
In case you need delayed expansion for both nested variables, you could use a for
loop:
@echo off
set "myString=something"
set "result=4"
setlocal EnableDelayedExpansion
echo !myString!
for %%I in (!Result!) do echo !myString:~%%I!
endlocal
This works because the for
variable %%I
is expanded before delayed expansion is applied, so the loop body receives the command line echo !myString:~4!
.