1

If I get my parameter with %1 and it is "Server" how can I add a + sign after every letter? So my result would be "S+e+r+v+e+r"?

I think Batch file to add characters to beginning and end of each line in txt file this is a similar question but I don't know how to change the code for this purpose.

Any help would be great!

Community
  • 1
  • 1
user754730
  • 1,341
  • 5
  • 31
  • 62

2 Answers2

3

This batch file should do it:

@ECHO OFF
SETLOCAL EnableDelayedExpansion

SET Text=%~1
SET Return=

REM Batch files don't have a LEN function.
REM So this loop will process up to 100 chars by doing a substring on each.
FOR /L %%I IN (0,1,100) DO (
    CALL SET Letter=!Text:~%%I,1!
    REM Only process when a letter is returned.
    IF NOT "!Letter!" == "" (
        SET Return=!Return!+!Letter!
    ) ELSE (
        REM Otherwise, we have reached the end.
        GOTO DoneProcessing
    )
)

:DoneProcessing
REM Remove leading char.
SET Return=%Return:~1,999%

ECHO %Return%

ENDLOCAL

Calling with Test.bat Server prints S+e+r+v+e+r to the console.

Jason Faulkner
  • 6,378
  • 2
  • 28
  • 33
3

I'm pretty sure this has been asked and answered before, but I couldn't find it.

There is a really cool (and fast) solution that I saw posted somewhere. It uses a new cmd.exe process with the /U option so output is in unicode. The interesting thing about the unicode is that each ASCII character is represented as itself followed by a nul byte (0x00). When this is piped to MORE, it converts the nul bytes into newlines!. Then a FOR /F is used to iterate each of the characters and build the desired string. A final substring operation is used to remove the extra + from the front.

I tweaked my memory of the code a bit, playing games with escape sequences in order to get the delayed expansion to occur at the correct time, and to protect the character when it is appended - all to get the technique to preserve ^ and ! characters. This may be a new twist to existing posted codes using this general technique.

@echo off
setlocal enableDelayedExpansion
set "str=Server bang^! caret^^"
set "out="
for /f delims^=^ eol^= %%A in ('cmd /u /v:on /c echo(^^!str^^!^|more') do set "out=!out!+^%%A"
set "out=!out:~1!"
echo Before: !str!
echo  After: !out!

--OUTPUT---

Before: Server bang! caret^
 After: S+e+r+v+e+r+ +b+a+n+g+!+ +c+a+r+e+t+^
dbenham
  • 127,446
  • 28
  • 251
  • 390