我正在尝试遍历字符串中的每个字符。然而,我只知道如何循环使用字符串中的每个单词:
(set /P MYTEXT=)<C:\MYTEXTFILE.txt
set MYEXAMPLE=%MYTEXT%
for %%x in (%MYEXAMPLE%) do (
ECHO DO SOMTHING
)
如何将其配置为按字符工作而不是每个字?
答案 0 :(得分:3)
AFAIK,FOR
无法进行字符迭代 - 可能的解决方法是构建一个这样的循环:
@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
注意:问题标题表明你要循环遍历&#34;变量字符串&#34;中的每个字符,这表明输入文件只包含一行,因为命令{ {1}} 只会读取 (set /P MYTEXT=)<C:\MYTEXTFILE.txt
的第一行。如果你想循环遍历文件中的所有行,解决方案有点复杂,我建议你再打开一个问题。
答案 1 :(得分:3)
这是循环遍历字符串中每个字符的简单直接方法:
@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
答案 2 :(得分:0)
下面的splitStr
子例程:
goto
循环errorLevel
设置为字符串@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%