Looping for every character in variable string BATCH

会有一股神秘感。 提交于 2019-12-21 14:32:54

问题


I'm trying to loop through every character in a string . I only however know how to loop for every word in a string ussing the following:

(set /P MYTEXT=)<C:\MYTEXTFILE.txt

set MYEXAMPLE=%MYTEXT%
for %%x in (%MYEXAMPLE%) do (
ECHO DO SOMTHING
)

How can I configure it to work per character rather then per word?


回答1:


AFAIK, FOR cannot do a character-wise iteration - A possible workaround is to build a loop like this:

@ECHO OFF
:: string terminator: chose something that won't show up in the input file
SET strterm=___ENDOFSTRING___
:: read first line of input file
SET /P mytext=<C:\MYTEXTFILE.txt
:: add string terminator to input
SET tmp=%mytext%%strterm%
:loop
:: get first character from input
SET char=%tmp:~0,1%
:: remove first character from input
SET tmp=%tmp:~1%
:: do something with %char%, e.g. simply print it out
ECHO char: %char%
:: repeat until only the string terminator is left
IF NOT "%tmp%" == "%strterm%" GOTO loop

Note: The question title states that you want to loop over "every character in variable string", which suggests the input file only contains a single line, because the command (set /P MYTEXT=)<C:\MYTEXTFILE.txt will only read the first line of C:\MYTEXTFILE.txt. If you want to loop over all lines in a file instead, the solution is a bit more complicated and I suggest you open another question for that.




回答2:


This is a simple and direct way to loop through every character in a string:

@echo off
setlocal ENABLEDELAYEDEXPANSION

set /P mytext= < MYTEXTFILE.txt
echo Line is '%mytext%'

set pos=0
:NextChar
    echo Char %pos% is '!mytext:~%pos%,1!'
    set /a pos=pos+1
    if "!mytext:~%pos%,1!" NEQ "" goto NextChar



回答3:


The splitStr subroutine below:

  • will print out every character in the string one by one
  • can be safely called regardless of the state of delayed expansion
  • has no superslow goto loop
  • handles CR and LF
  • sets the errorLevel to the number of characters in the string
@echo off & setLocal enableExtensions disableDelayedExpansion
(call;) %= sets errorLevel to 0 =%

set "testStr=uncopyrightable"
call :splitStr testStr
if errorLevel 1 (
    >&2 echo(string is %errorLevel% char(s^) in length
) else (
    >&2 echo(empty string
    goto die
) %= if =%
goto end

:die
(call) %= sets errorLevel to 1 =%
:end
endLocal & goto :EOF

:splitStr string=
:: outputs string one character per line
setLocal disableDelayedExpansion
set "var=%1"

set "chrCount=0" & if defined var for /f "delims=" %%A in ('
    cmd /v:on /q /c for /l %%I in (0 1 8190^) do ^
    if "!%var%:~%%I,1!" neq "" (^
    echo(:^!%var%:~%%I^,1^!^) else exit 0
') do (
    set /a chrCount+=1
    echo%%A
) %= for /f =%

endLocal & exit /b %chrCount%


来源:https://stackoverflow.com/questions/15004825/looping-for-every-character-in-variable-string-batch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!