7

我正在尝试遍历 string 中的每个字符。但是,我只知道如何使用以下方法循环字符串中的每个单词:

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

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

如何将其配置为按字符而不是按单词工作?

4

3 回答 3

6

这是遍历字符串中每个字符的简单直接的方法:

@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
于 2016-07-29T16:26:05.007 回答
4

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

注意:问题标题表明您要循环遍历“变量字符串中的每个字符”,这表明输入文件仅包含一行,因为该命令(set /P MYTEXT=)<C:\MYTEXTFILE.txt 只会读取 C:\MYTEXTFILE.txt. 如果您想遍历文件中的所有行,则解决方案有点复杂,我建议您为此打开另一个问题。

于 2013-02-21T18:14:55.747 回答
0

下面的splitStr子程序:

  • 将逐个打印出字符串中的每个字符
  • 无论延迟扩展的状态如何,都可以安全地调用
  • 没有超慢goto循环
  • 处理 CR 和 LF
  • 设置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%
于 2017-12-28T18:56:55.497 回答