Given that the input string does not contain one of the characters !
, ^
and "
, and that there are no adjacent spaces (which would be compressed to one), the following code works:
@echo off
setlocal EnableDelayedExpansion
set "string=what a string"
set "new=" & set "wrd=" & set "aug=%string% "
set "new=%aug: =" & (if defined wrd if not "!wrd:~1!"=="" set "new=!new! !wrd!") & set "wrd=%"
echo original: "%string%"
echo modified: "%new%"
endlocal
To maintain adjacent spaces, modify the script like this:
@echo off
setlocal EnableDelayedExpansion
set "string=what a nice string"
set "new=" & set "wrd= " & set "aug=%string% "
set "new=%aug: =" & (if not "!wrd:~1!"=="" set "new=!new! !wrd!") & set "wrd=%"
echo original: "%string%"
echo modified: "%new%"
endlocal
Thanks to Aacini for the hint!