0
我試圖在批處理中編寫文本冒險,所以我想知道如何拆分變量,如set userinput = take book並將其變爲數組。我希望能夠編寫一個將字符串拆分爲數組項的程序。我用很多其他語言做了這個。還有其他幾個這樣的問題,但我不覺得他們回答我的問題。如何在批處理中將變量拆分爲數組
我試圖在批處理中編寫文本冒險,所以我想知道如何拆分變量,如set userinput = take book並將其變爲數組。我希望能夠編寫一個將字符串拆分爲數組項的程序。我用很多其他語言做了這個。還有其他幾個這樣的問題,但我不覺得他們回答我的問題。如何在批處理中將變量拆分爲數組
這個任務可能比你意識到的要困難得多。有很多「簡單」的方法,但沒有一個簡單的方法是健壯的。
例如,一個簡單的FOR循環可以解析出單個標記,但它將被打破*
,?
,並可能"
。
一個強大的解決方案需要大量的代碼。
這裏是我的解決方案,廣泛徵求意見:
@echo off
:: Start out with delayed expansion disabled, and define "user input"
:: I intentionally include "problem" characters
setlocal disableDelayedExpansion
set "userinput=take book! & ;MustPreserve EmptyLinesAreIgnored"
:: Initialize count
set "cnt=0"
:: Enable and use delayed expansion to protect against poison characters
setlocal enableDelayedExpansion
:: Substitute <LineFeed> for each <space>
(set parsed=!userinput: =^
%= Do not remove or alter this line =%
!)
:: Iterate each line, setting delims and eol to <space> to preserve all tokens
for /f "eol= delims= " %%A in ("!parsed!") do (
%= Return to delayed expansion disabled on first iteration, else ! is lost =%
if "!" equ "" endlocal
%= Increment the count =%
set /a cnt+=1
%= Temporarily enable delayed expansion to capture current count in FOR variable =%
setlocal enableDelayedExpansion
for %%N in (!cnt!) do (
endlocal
%= Save the array value =%
set "token.%%N=%%A"
)
)
::Print the results. Safe array access requires delayed expansion
setlocal enableDelayedExpansion
for /l %%N in (1 1 !cnt!) do echo token.%%N=!token.%%N!
它看起來沒有所有的評論
@echo off
setlocal disableDelayedExpansion
set "userinput=take book! & :MustPreserveColon ;MustPreserve EmptyLinesAreIgnored"
set "cnt=0"
setlocal enableDelayedExpansion
(set parsed=!userinput: =^
%= Do not remove or alter this line =%
!)
for /f "eol= delims= " %%A in ("!parsed!") do (
if "!" equ "" endlocal
set /a cnt+=1
setlocal enableDelayedExpansion
for %%N in (!cnt!) do (
endlocal
set "token.%%N=%%A"
)
)
setlocal enableDelayedExpansion
for /l %%N in (1 1 !cnt!) do echo token.%%N=!token.%%N!
這裏好一點的輸出:
token.1=take
token.2=book!
token.3=&
token.4=;MustPreserve
token.5=EmptyLinesAreIgnored