Logan Cunningham
Logan Cunningham

Reputation: 30

The use of a variable in a variable

I cannot use a variable '%a' inside of variable 'varname' in this code:

@echo of
set varname=stringhere
for /l %%a in (1,1,10) do (
    echo %varname:~1,%%a%
    ping -n 0.01 >nul
)

But what it displays is:

a% a% a% a% a% a% a% a% a% a%

What I want it to display as:

s st str stri strin string stringh stringhe stringher stringhere

So in words I am trying to optimize my code as much as possible and I want to make a function that prints out a variable one letter at a time but it isn't letting me use substring in the way I want it to..

Upvotes: 0

Views: 115

Answers (2)

Magoo
Magoo

Reputation: 80123

@ECHO OFF
SETLOCAL
set varname=stringhere
for /l %%a in (1,1,10) do (
    CALL echo %%varname:~0,%%a%%
)
GOTO :EOF

Note that strings start at character 0.

Upvotes: 3

RGuggisberg
RGuggisberg

Reputation: 4750

This should do what you want, including the leading space that it looks like you have in your desired output. Remove the REM below if you want to remove the leading space.

@echo off
setlocal enabledelayedexpansion
set varname=stringhere
set "OutString="
for /l %%a in (1,1,10) do set OutString=!OutString! !varname:~0,%%a!
REM set OutString=%OutString:~1%
echo.%OutString%
pause

Upvotes: 2

Related Questions