0

To convert string of words into an array in batch script, I wrote a small script

setlocal enableextensions enabledelayedexpansion
echo run

set sentence=a~b~c

set /a i=0

for /f "tokens=1,2,3 delims=~" %%a in ("%sentence%") do (
   set /a i+=1
   set array[!i!]=%%a
)

echo %array[1]%
echo %array[2]%

But there is some problem with this logic as only first element gets assigned. How can i correct this.

1
  • 1
    FTR: This merely emulates an array by sporting array-like variable names. It doesn't create an actual array. Commented Sep 10, 2013 at 17:58

2 Answers 2

5

the FOR command parses the contents of your variable into consecutive variable %a %b %c...

read HELP FOR and try, in your case,

for /f "tokens=1,2,3 delims=~" %%a in ("%sentence%") do (
   set array[1]=%%a
   set array[2]=%%b
   set array[3]=%%c
)
echo %array[1]%
echo %array[2]%

for a more generic parser loop, you will need a very tricky technique of changing your delimiters into line separators. See this SO answer https://stackoverflow.com/a/12630844/30447 for a comprehensive explanation.

Sign up to request clarification or add additional context in comments.

Comments

3

If you can space-delimit the string instead, this should work for you.

@echo off
setlocal ENABLEDELAYEDEXPANSION
REM String, with words separated by spaces
set sentence=x y z

set index=0
for %%A in (%sentence%) do (
    set Array[!index!] = %%A
    set /a index += 1
)

echo.There are %index% words
set Array

Output:

F:\scripting\stackoverflow>s2a2.cmd
There are 3 words
Array[0] = x
Array[1] = y
Array[2] = z

3 Comments

This will print correct output on console. If i want to have three variables say var1, var2, var3 or array[1],array[2] and array[3] and i want to assign values x, y and z to them for further use, what is the correct way.
This solution does that for you. The 'set Array' command displays all variables that start with the word "Array". Variable %ARRAY[0]% is equal to "x", %ARRAY[1]% is equal to "y", and %ARRAY[2]% is equal to "z". You can use those throughout the rest of your script or at the command line. If you want to do something with all of the variables, do something like: for /f "tokens=2,* delims==[]" %%A in ('set Array') do echo.Array variable %%A is equal to %%B Let me know if I didn't understand your question.
@MJeremyCarter trying to print echo %Array[1]% results in ECHO is off. message

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.