【问题标题】:Batch For loop array批处理 For 循环数组
【发布时间】:2013-04-23 15:36:59
【问题描述】:

好的,这就是我所拥有的。

@echo off
setLocal EnableDelayedExpansion
:begin
set /a M=0
set /a number=0
set /p Input=You: 
echo %Input% >> UIS
for /F "tokens=1 delims= " %%i in ("%Input%") do (
    set /a M+=1
    set i!M!=%%i
)
del UIS 1>nul 2>nul
:loop
set /a number+=1
set invar=!i%number%!
echo %invar%
pause > nul
goto loop

例如,输入字符串是“大声笑这是我的输入字符串” 我希望 for 循环设置 i!M!其中 M = 1 到“Lol”,其中 M = 2 i!M!是“这个”,其中 M = 3 i!M!是“是”等等。现在,当然,这不能永远持续下去,所以即使我必须在 M = 25 时停止,并说字符串只有 23 个字长。然后当 M = 24 和 25 时 i!M!只是 null 或未定义。

感谢您的帮助,谢谢。

【问题讨论】:

  • 告诉我们脚本有什么问题。
  • 好吧,它只是从字符串中读取第一个单词,并且不会将 M 的值设置为超过 1。

标签: loops for-loop batch-file cmd


【解决方案1】:

for /f 逐行读取,而不是逐字读取。

这是How to split a string in a Windows batch file? 提出的答案,并根据您的情况进行了修改:

@echo off
setlocal ENABLEDELAYEDEXPANSION

REM Set a string with an arbitrary number of substrings separated by semi colons
set teststring=Lol this is my input string
set M=0

REM Do something with each substring
:stringLOOP
    REM Stop when the string is empty
    if "!teststring!" EQU "" goto displayloop

    for /f "delims= " %%a in ("!teststring!") do set substring=%%a

    set /a M+=1
    set i!M!=!substring!

    REM Now strip off the leading substring
    :striploop
        set stripchar=!teststring:~0,1!
        set teststring=!teststring:~1!

        if "!teststring!" EQU "" goto stringloop

        if "!stripchar!" NEQ " " goto striploop

        goto stringloop

:displayloop
set /a number+=1
set invar=!i%number%!
echo %invar%
pause > nul
goto displayloop

endlocal

【讨论】:

    【解决方案2】:

    for /F 命令将一行分成确定个必须通过不同的可替换参数(%%i、%%j 等)一次处理的令牌。普通的for 命令将一行分割成 undefined 个单词(由空格、逗号、分号或等号分隔),这些单词在迭代循环中逐个处理。这样,您只需将其更改为:

    for /F "tokens=1 delims= " %%i in ("%Input%") do (
    

    这个:

    for %%i in (%Input%) do (
    

    PS - 我建议你将数组写成标准格式,将下标括在方括号中;这样更清楚:

    set i[!M!]=%%i
    

    set invar=!i[%number%]!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-19
      • 2015-04-17
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多