Discussion forum for all Windows batch related topics.
Moderator: DosItHelp
-
Cornbeetle
- Posts: 31
- Joined: 23 Nov 2015 09:34
#1
Post
by Cornbeetle » 28 Oct 2016 11:19
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
-
LotPings
- Posts: 10
- Joined: 26 Oct 2016 22:45
#2
Post
by LotPings » 28 Oct 2016 12:19
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"
-
aGerman
- Expert
- Posts: 4678
- Joined: 22 Jan 2010 18:01
- Location: Germany
#3
Post
by aGerman » 28 Oct 2016 13:09
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
-
Cornbeetle
- Posts: 31
- Joined: 23 Nov 2015 09:34
#4
Post
by Cornbeetle » 28 Oct 2016 13:30
Thank you LotPings and aGerman, all of these are helpful and do exactly what I need.