在Windows Batch中以可变长度分割字符串 [英] Split string with variable length in Windows Batch
问题描述
我实际上正在编写代码/解码器.现在,我必须将数字组与其他组分开.数字组的长度是未知的,但我知道它们会被"(空格字符)除.我不知道如何进行,但是我可以用伪代码解释我的遗嘱:
I'm actually working on a codifier/decodifier. Now I have to separate numeric groups from others. The length of the numeric groups is unknown but I know they are divided by " " (a space char). I don't know how to proceed, but I can explain my will with a pseudo-code:
for x-times (maybe the maximum, like 128) (
group[index] = the first part of the string until " "
string = string minus the first part until " "
)
基本上,我想将组提取到单个数组中.这可能吗?我尝试了很多使用已定义标记的方法,但是我的系统却完全不同.
Basically, I want to extract the groups in a single array. Is this possible? I tried a lot of methods with defined tokens, but my system is completely different.
推荐答案
正如Mofi已经指出的那样,简单的 for
就能解决问题.添加一个计数器以为每个单词"(数组)建立一个变量.它们是实词还是数字都没有关系,但是某些特殊字符会产生错误,例如&
, |
或被忽略,例如%
,!
).
As Mofi already noted, a simple for
will do the trick. Add a counter to build up a variable for every "word" (array). Whether they are real words or numbers doesn't matter, but some special chars will generate errors, like &
, |
or just being ignored, like %
, !
).
@echo off
setlocal enabledelayedexpansion
set count=0
set "string=some substrings with variable lengths separated by space"
for %%a in (%string%) do (
set /a count+=1
set substring[!count!]=%%a
)
set substring[
这篇关于在Windows Batch中以可变长度分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!