如何在LOOP中动态拆分字符串

时间:2018-04-20 13:26:38

标签: batch-file

如何在LOOP中动态分割字符串

我想在LOOP中动态分割字符串,但下面的代码不能正常工作, 它看起来很简单,但实际上让我的编码工作不正常让我很困惑, 也许可以采用另一种方法吗?

*额外的问题,如何在单循环中获得字符串长度。

sample.bat:

@echo off & setlocal EnableDelayedExpansion

:: Configuration
set "Num_1= 123"
set "Num_2= 45"
set "Num_3= 6789"
::set "Num_4= 4343321345677"
::set "Num_5= 98987675567543213"
::set "Num_6= 6766578987765544339"
::set "char1= anf,ki"
::set "char2= aewr(677)ni"


:: Get length 
:length 
if not "!Num_1:~%len%!"=="" set /A len+=1 & goto length 
set /A L_Num_1=%len% - 1 
set len=0

:length2
if not "!Num_2:~%len%!"=="" set /A len+=1 & goto length2
set /A L_Num_2=%len% - 1 
set len=0

:length3
if not "!Num_3:~%len%!"=="" set /A len+=1 & goto length3
set /A L_Num_3=%len% - 1 


Set Count="

:: Split
set "cha=1"
for /l %%n in (1,1,3) do (
       Set Count="
               for /l %%o in (!L_Num_%cha%!,-1,0) do (
              Set /a "cha=cha + 1 | 1 "
              Set /a "Count+=1"
              set "SNum(%%n)_!Count!=!Num_%%n:~%%o,1!"
         )
 )
set SNum
pause

当前输出

SNum(1)_7=3
SNum(1)_8=2
SNum(1)_9=1
SNum(1)_10= 

SNum(2)_2=5
SNum(2)_3=4
SNum(2)_4= 

SNum(3)_1=8
SNum(3)_2=7
SNum(3)_3=6 
SNum(3)_4=

输出我需要的东西

(from Variable Num_1 )

SNum(1)_1=3
SNum(1)_2=2
SNum(1)_3=1

(from Variable Num_2 )

SNum(2)_1=5
SNum(2)_2=4

(from Variable Num_3 )

SNum(3)_1=9
SNum(3)_2=8
SNum(3)_3=7
SNum(3)_4=6

从后向拆分每个变量/字符串,并从1开始创建新数组。 我知道可以通过从变量中逐个手动拆分字符串来完成,但在我的情况下,我已经动态拆分,因为不仅有三个字符串来自变量i必须拆分,有时它有超过10个变量。

1 个答案:

答案 0 :(得分:1)

用于获取字符串长度的方法是测试最大长度中间的字符,并连续将此最大长度减半。净效果就像收集实际字符串长度的各个位(基数为2:1,2,4,8等)。

@echo off
setlocal EnableDelayedExpansion

:: Configuration
set "Num_1=123"
set "Num_2=45"
set "Num_3=6789"

rem Set number of variables to process
set "vars=3"

rem Get length of "Num_1".."Num_%vars%" variables into "L_Num_1".."L_Num_%vars%"
for /L %%n in (1,1,%vars%) do (
   set "L_Num_%%n=0"
   for /L %%a in (12,-1,0) do (
      set /A "newLen=L_Num_%%n+(1<<%%a)"
      for %%b in (!newLen!) do if "!Num_%%n:~%%b,1!" neq "" set "L_Num_%%n=%%b"
   )
)

rem Split %vars% variables into individual characters
for /L %%n in (1,1,%vars%) do (
   set "cha=0"
   for /L %%o in (!L_Num_%%n!,-1,0) do (
      set /A "cha=cha+1"
      set "SNum[%%n]_!cha!=!Num_%%n:~%%o,1!"
   )
)
set SNum

请注意,第一个测试位置是2^12,即4096,即最大字符串长度的一半。这是通过左移位操作实现的:1<<%%a