0

Let's say we have number "256" And I want my program to detect that first digit from left is 2, second 5, third 6

Do you have any ideas or is there certain command?

  • 2
    http://stackoverflow.com/questions/636381/what-is-the-best-way-to-do-a-substring-in-a-batch-file might help you with using substring and this will help with IF statements http://ss64.com/nt/if.html – zedfoxus Oct 02 '15 at 15:50
  • 1
    `if %number% equ 256 echo First digit is 2, second digit is 5 and third is 6` – Aacini Oct 02 '15 at 17:39

3 Answers3

0

You can use the syntax for variable substring expansion -- type set /? in the console to get more information:

set NUM=256
echo 1st digit:  %NUM:~0,1%
echo 2nd digit:  %NUM:~1,1%
echo 3rd digit:  %NUM:~2,1%
aschipfl
  • 33,626
  • 12
  • 54
  • 99
0

You can use aschipfl's method as well as you only have string with 3 individual substrings. Anyway, my method do work for 0 ~ max length of string.

@echo off
setlocal EnableDelayedExpansion

set "myvar=some_string"
set "define_myvar=%myvar%"
set length=0

echo Original String: %myvar%
echo.

:loop
if defined define_myvar (
    set define_myvar=!define_myvar:~1!
    set substr=!myvar:~%length%,1!

    echo !substr!

    set /a length += 1
    goto :loop
)

pause >nul
Happy Face
  • 1,061
  • 7
  • 18
0

Here's the complicated way. It loops 10 digits (to cover 32-bit unsigned integers). A for /L loop is often faster than a goto loop.

@echo off
setlocal enabledelayedexpansion

set "num=256"

for /L %%I in (0,1,9) do (
    if "!num:~%%I,1!"=="" goto break
    set /a "digit[%%I] = !num:~%%I,1!"
)
:break

echo %num%
rem // display digit[] array
set digit

Output:

256
digit[0]=2
digit[1]=5
digit[2]=6

rojo
  • 24,000
  • 5
  • 55
  • 101