为了账号安全,请及时绑定邮箱和手机立即绑定

如何在Windows批处理文件中按空格分割字符串?

如何在Windows批处理文件中按空格分割字符串?

慕森王 2019-12-25 14:48:25
假设我有一个字符串“ AAA BBB CCC DDD EEE FFF”。如何在批处理文件中拆分字符串并检索第n个子字符串?C#中的等效项为"AAA BBB CCC DDD EEE FFF".Split()[n]
查看完整描述

3 回答

?
千巷猫影

TA贡献1829条经验 获得超7个赞

看HELP FOR例子


或快速尝试一下


 for /F %%a in ("AAA BBB CCC DDD EEE FFF") do echo %%c


查看完整回答
反对 回复 2019-12-25
?
四季花海

TA贡献1811条经验 获得超5个赞

遍历字符串的三个可能的解决方案:


版本1:


@echo off & setlocal

set s=AAA BBB CCC DDD EEE FFF

for %%a in (%s%) do echo %%a

版本2:


@echo off & setlocal

set s=AAA BBB CCC DDD EEE FFF

set t=%s%

:loop

for /f "tokens=1*" %%a in ("%t%") do (

   echo %%a

   set t=%%b

   )

if defined t goto :loop

版本3:


@echo off & setlocal

set s=AAA BBB CCC DDD EEE FFF

call :sub1 %s%

exit /b

:sub1

if "%1"=="" exit /b

echo %1

shift

goto :sub1

当字符串包含通配符(例如“ *”或“?”)时,版本1不起作用。


版本1和版本3处理字符,例如'=',';' 或','作为单词分隔符。这些字符与空格字符具有相同的效果。


查看完整回答
反对 回复 2019-12-25
?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

以下代码将使用任意数量的子字符串分割字符串:


@echo off

setlocal ENABLEDELAYEDEXPANSION


REM Set a string with an arbitrary number of substrings separated by semi colons

set teststring=The;rain;in;spain


REM Do something with each substring

:stringLOOP

    REM Stop when the string is empty

    if "!teststring!" EQU "" goto END


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


        REM Do something with the substring - 

        REM we just echo it for the purposes of demo

        echo !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

)


:END

endlocal


查看完整回答
反对 回复 2019-12-25
  • 3 回答
  • 0 关注
  • 1782 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信