Page 1 of 1

Insert a space between every character in a given string?

Posted: 28 Oct 2016 11:19
by Cornbeetle
I have a string of numbers set to variable "num". How can I insert a space in between each number to get the desired result below?

Code: Select all

set num=2212221

??????
??????

echo %numWithSpaces%
2 2 1 2 2 2 1


I could chop it up like this

Code: Select all

%num:~0,1% %num:~1,1% %num:~2,1% ...


But if I dont know the string length I don't know how many times to to create a substring...



-CB

Re: Insert a space between every character in a given string?

Posted: 28 Oct 2016 12:19
by LotPings
Hello cornbeetle,
if you take char by char from the beginning until at end of the string you don't need to know the length. You may count while looping.

Code: Select all

@Echo off
set num=2212221
echo "%num%"
Set numtemp=%num%
Set "num="
:loop
Set "num=%num% %numtemp:~0,1%"
Set "numtemp=%numtemp:~1%
if defined numtemp goto :loop
Set num=%num:~1%
echo "%num%"


OutPut:

Code: Select all

> InsertSpaces.cmd
"2212221"
"2 2 1 2 2 2 1"

Re: Insert a space between every character in a given string?

Posted: 28 Oct 2016 13:09
by aGerman
Choose one of these 3 possibilities.

Code: Select all

@echo off &setlocal

set "num=2212221"

set "numWithSpaces="
setlocal EnableDelayedExpansion
for /f %%i in ('cmd /v:on /u /c "echo(!num!"^|find /v ""') do set "numWithSpaces=!numWithSpaces!%%i "
endlocal &set "numWithSpaces=%numWithSpaces:~,-1%"
echo "%numWithSpaces%"

set "numWithSpaces=%num%"
setlocal EnableDelayedExpansion
for /l %%i in (0 1 9) do set "numWithSpaces=!numWithSpaces:%%i=%%i !"
endlocal &set "numWithSpaces=%numWithSpaces:~,-1%"
echo "%numWithSpaces%"

set "numWithSpaces="
setlocal EnableDelayedExpansion
set "n=0"
:loop
if "!num:~%n%,1!" neq "" (set "numWithSpaces=!numWithSpaces!!num:~%n%,1! " &set /a "n+=1" &goto loop)
endlocal &set "numWithSpaces=%numWithSpaces:~,-1%"
echo "%numWithSpaces%"

pause

Steffen

Re: Insert a space between every character in a given string?

Posted: 28 Oct 2016 13:30
by Cornbeetle
Thank you LotPings and aGerman, all of these are helpful and do exactly what I need.