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

如何在Batch中利用字符串长度实现字符串转大写?

问题分析与解决方案

你的核心问题在于:CLEANER函数里的语法错误,批处理不支持SET $str:[POSITION @ $len]=$str:[POSITION @ $len]这种位置赋值的写法,且字符串大小写转换需要明确处理每个字符。以下是修正后的代码和说明:

修正后的完整代码

@ECHO on
TITLE Navigator
SETLOCAL enabledelayedexpansion

REM | ...file comments...

REM | variable setting, grabbing & cleaning
SET _box=%1
SET _system=%_box:~1,-1%
CALL :STRLEN _system _len
CALL :CLEANER _system _len _cSystem

REM | Results
ECHO Cleaned output: %_cSystem%

PAUSE
ENDLOCAL
EXIT /B %ERRORLEVEL%

REM | ***** Functions *****
REM | String length function (last working @ 09/26/22 TIME)
:STRLEN
  SET $str=!%1!
  SET $len=0
:_STRLEN
  IF NOT DEFINED $str ( goto :END_STRLEN )
  IF NOT "!$str:~%$len%!"=="" (
    SET /A $len+=1
    goto :_STRLEN
  )
:END_STRLEN
  SET "%2=!$len!"
  SET $str=
  SET $len=
  EXIT /B 0

REM | String cleaner (fixed to convert to uppercase)
:CLEANER
  SET $str=!%1!
  SET $len=!%2!
  SET $result=
  SET $index=0
:_CLEANER_LOOP
  REM 终止循环:当索引超过字符串长度时跳出
  IF !$index! GEQ !$len! GOTO :END_CLEANER
  REM 提取当前索引位置的单个字符
  SET $char=!$str:~%$index%,1!
  REM 将小写字符转为大写(覆盖所有26个英文字母)
  SET $char=!$char:a=A!
  SET $char=!$char:b=B!
  SET $char=!$char:c=C!
  SET $char=!$char:d=D!
  SET $char=!$char:e=E!
  SET $char=!$char:f=F!
  SET $char=!$char:g=G!
  SET $char=!$char:h=H!
  SET $char=!$char:i=I!
  SET $char=!$char:j=J!
  SET $char=!$char:k=K!
  SET $char=!$char:l=L!
  SET $char=!$char:m=M!
  SET $char=!$char:n=N!
  SET $char=!$char:o=O!
  SET $char=!$char:p=P!
  SET $char=!$char:q=Q!
  SET $char=!$char:r=R!
  SET $char=!$char:s=S!
  SET $char=!$char:t=T!
  SET $char=!$char:u=U!
  SET $char=!$char:v=V!
  SET $char=!$char:w=W!
  SET $char=!$char:x=X!
  SET $char=!$char:y=Y!
  SET $char=!$char:z=Z!
  REM 将转换后的字符拼接到结果字符串
  SET $result=!$result!!$char!
  REM 索引自增,继续处理下一个字符
  SET /A $index+=1
  GOTO :_CLEANER_LOOP
:END_CLEANER
  SET "%3=!$result!"
  REM 清理临时变量,避免污染
  SET $str=
  SET $len=
  SET $result=
  SET $index=
  SET $char=
  EXIT /B 0

关键修正点

  1. 循环逻辑修正:

    • 新增$index变量作为字符位置索引,从0开始遍历到字符串长度-1
    • 用IF !$index! GEQ !$len!判断循环终止条件,替换原来错误的字符串比较IF "$len">=0
  2. 字符大小写转换:

    • 用!$str:~%$index%,1!提取指定位置的单个字符
    • 通过逐个替换小写字母为大写的方式实现转换(批处理原生不支持一键转大写,需手动覆盖所有字母)
    • 将转换后的字符逐步拼接到$result变量,最终赋值给输出参数
  3. 语法错误修复:

    • 删除了无效的SET $str:[POSITION @ $len]=$str:[POSITION @ $len]语句,替换为符合批处理语法的字符提取与拼接逻辑

简化替代方案(可选)

如果不需要逐个字符处理的逻辑,批处理可以结合PowerShell实现一键转大写,代码更简洁:

REM 替换原来的CALL :CLEANER语句
FOR /F "delims=" %%a IN ('powershell -Command "\"!_system!\" -toUpper"') DO SET "_cSystem=%%a"

这种方式无需自己写循环,直接利用PowerShell的字符串转换能力,适合不需要复杂自定义逻辑的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 04:05:13