0

I want to echo a single digit from a string assigned to a variable, but the position of the echoed digit would be determined by another variable.
Something like:

set a=ABCDEF
set b=3
echo %a:~%b%,1%

As if you wanted to echo the 3rd digit in the ABCDEF string this would be the same as:

echo %a:~3,1%

The reason im trying to do it this way is because the b variable will be prompted from the user several times with different values.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Inter1k
  • 11
  • 3
  • It's "Dynamic substring". – Til Jan 12 '19 at 14:19
  • 1
    Check out [this](https://stackoverflow.com/questions/8913453/) – Til Jan 12 '19 at 14:20
  • Sure thing. Please edit your post better next time, make use those buttons on the editor. For example the `{}` button can easily format your code block. – Til Jan 12 '19 at 14:30
  • 3
    Your statement is absolutely incorrect. If you want to echo the 3rd digit, you'd use `echo %a:~2,1%`. This of course means that if the content of `%b%` is being entered by the end user, for instance, you'd need to use `set /a` to deduct `1` from it first. As for your question problem you have two choices, either enable delayed expansion and use, `echo !a:~%b%,1!`, or use a call statement like this, `call echo %%a:~%b%,1%%`. – Compo Jan 12 '19 at 14:38
  • 2
    This type of management is described at [this answer](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990), although the topic is different... – Aacini Jan 12 '19 at 15:32

2 Answers2

1

An example showing both methods:

@Echo Off
SetLocal DisableDelayedExpansion
Set "str=VALUE"
Echo Your string is %str%

Choice /C 12345 /M "Choose a positional digit"
Set /A int=%ERRORLEVEL%-1
Call Echo Your positional digit matches the character %%str:~%int%,1%%

Timeout 2 /NoBreak >Nul

Choice /C 12345 /M "Choose a positional digit"
Set /A int=%ERRORLEVEL%-1
SetLocal EnableDelayedExpansion
Echo Your positional digit matches the character !str:~%int%,1!
EndLocal

Timeout -1
Compo
  • 36,585
  • 5
  • 27
  • 39
0

You would need to enabledelayedexpansion

see set /? and setlocal /? from cmd console.

@echo off
setlocal enabledelayedexpansion
set a=ABCDEF
set b=3
echo !a:~%b%,1!

Also, take not that effectively we start counting at 0, so b=3 would result in echoing D

Gerhard
  • 22,678
  • 7
  • 27
  • 43