You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

for /f循环字符串拆分异常求助:首空格后内容无法完整获取

批处理字符串拆分问题解决

你的问题出在tokens=2*的用法上,并非变量设置错误。

在批处理的for /f指令中,当使用tokens=2*时:

  • 指定的第一个循环变量(此处为%%g)仅对应第2个独立的token(也就是单个单词these)
  • *所匹配的第一个空格之后的全部剩余内容,会自动赋值给下一个顺序的循环变量(即%%h)

你之前直接将%%g赋值给second,自然只能拿到单个单词。

修正后的代码(拆分两个循环)

@echo off
set string=alone these are together
for /f "tokens=1" %%g IN ("%string%") do set first=%%g
for /f "tokens=2*" %%g IN ("%string%") do set second=%%h
echo %first%
echo %second%
pause

更高效的单循环写法

可以用一个for /f循环同时完成两个变量的赋值,代码更简洁:

@echo off
set string=alone these are together
for /f "tokens=1*" %%g IN ("%string%") do (
    set first=%%g
    set second=%%h
)
echo %first%
echo %second%
pause

以上两种写法都能输出你期望的结果:

alone
these are together

内容的提问来源于stack exchange,提问作者Chaos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 20:15:27