Is there any way to add spaces after each letter in a text string?
For example, "cat" would become "c a t ".
Spaces can be removed later by using "set str=!str: =!". However, doing this in reverse doesn't work.
Any ideas?
Adding spaces to a text string.
Moderator: DosItHelp
Re: Adding spaces to a text string.
Sure, there are lots of ways to do it. But there is not a simple command that will do it.
Here is a very simple but relatively slow solution
I trimmed the last space at the end because your original requirement was to put a space between all the characters. You can certainly remove the set "str2=!str2:~0,-1!" line to preserve the trailing space.
Adding significantly more code can actually make the process faster. Using the highly optimized DosTips strLen function allows us to compute the length of the string, and then we can build the modified string using a very efficient FOR /L loop instead of the slow GOTO loop.
Dave Benham
Here is a very simple but relatively slow solution
Code: Select all
@echo off
setlocal enableDelayedExpansion
set "str=Here is a sample string"
set n=0
set "str2="
:loop
set "str2=!str2!!str:~%n%,1! "
set /a n+=1
if "!str:~%n%,1!" neq "" goto loop
set "str2=!str2:~0,-1!"
echo original string="!str!"
echo modified string="!str2!"
I trimmed the last space at the end because your original requirement was to put a space between all the characters. You can certainly remove the set "str2=!str2:~0,-1!" line to preserve the trailing space.
Adding significantly more code can actually make the process faster. Using the highly optimized DosTips strLen function allows us to compute the length of the string, and then we can build the modified string using a very efficient FOR /L loop instead of the slow GOTO loop.
Code: Select all
@echo off
setlocal enableDelayedExpansion
set "str=Here is a sample string"
set "str2="
call :strlen str len
set /a len-=1
for /l %%n in (0 1 %len%) do set "str2=!str2!!str:~%%n,1! "
set "str2=!str2:~0,-1!"
echo original string="!str!"
echo modified string="!str2!"
exit /b
:strLen string len -- returns the length of a string
:: -- string [in] - variable name containing the string being measured for length
:: -- len [out] - variable to be used to return the string length
:: Many thanks to 'sowgtsoi', but also 'jeb' and 'amel27' dostips forum users helped making this short and efficient
:$created 20081122 :$changed 20101116 :$categories StringOperation
:$source http://www.dostips.com
( SETLOCAL ENABLEDELAYEDEXPANSION
set "str=A!%~1!"&rem keep the A up front to ensure we get the length and not the upper bound
rem it also avoids trouble in case of empty string
set "len=0"
for /L %%A in (12,-1,0) do (
set /a "len|=1<<%%A"
for %%B in (!len!) do if "!str:~%%B,1!"=="" set /a "len&=~1<<%%A"
)
)
( ENDLOCAL & REM RETURN VALUES
IF "%~2" NEQ "" SET /a %~2=%len%
)
EXIT /b
Dave Benham