ABA*_*UNT 6 loops character batch-file
我正在尝试遍历字符串中的每个字符.然而,我只知道如何循环字符串中的每个单词,如下所示:
(set /P MYTEXT=)<C:\MYTEXTFILE.txt
set MYEXAMPLE=%MYTEXT%
for %%x in (%MYEXAMPLE%) do (
ECHO DO SOMTHING
)
Run Code Online (Sandbox Code Playgroud)
如何将其配置为按字符工作而不是每个字?
这是循环遍历字符串中每个字符的简单而直接的方法:
@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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
注意:问题标题指出您要循环遍历“变量字符串中的每个字符”,这表明输入文件仅包含一行,因为该命令(set /P MYTEXT=)<C:\MYTEXTFILE.txt 只会读取 C:\MYTEXTFILE.txt. 如果您想循环遍历文件中的所有行,解决方案会稍微复杂一些,我建议您为此打开另一个问题。