Windows Batch: Split String to individual characters to variables

丶灬走出姿态 提交于 2020-01-25 05:36:30

问题


in Windows Batch, if I had a variable (length can change) that was, for example: "hello world!" is it possible to "split" the variable so each character is its own variable so the output could look like:

t1=h
t2=e
t3=l
etc.

Any help would be appreciated.


回答1:


Use this code:

setlocal EnableDelayedExpansion
set str="hello world^!"
set tempstr=%str%
set count=0
:loop
if defined tempstr (
    set tempstr=%tempstr:~1%
    set /a count+=1
    set /a pos=%count%-1
    set t!count!=!str:~%pos%,1!
    goto loop
)

:: check the generated variables
set t

To get the nth character in a string, use set char=%str:~n,1%.
I hope this was helpful!




回答2:


Here is a variant using for /L to iterate over all characters of the string. The number of characters, so the length of the string, is retrieved in sub-routine :LENGTH first:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_STRING=Hello world!"

call :LENGTH LEN "%_STRING%"
setlocal EnableDelayedExpansion
for /L %%I in (0,1,%LEN%) do (
    set "$CHR[%%I]=!_STRING:~%%I,1!"
)
set $CHR
endlocal

endlocal
exit /B


:LENGTH  rtn_length  val_string
setlocal DisableDelayedExpansion
set /A "RET=0" & set "STR=%~2"
if defined STR set /A "RET=1"
setlocal EnableDelayedExpansion
for %%L in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
    if not "!STR:~%%L,1!"=="" (
        set /A "RET+=%%L"
        set "STR=!STR:~%%L!"
    )
)
(
    endlocal
    endlocal
    set "%~1=%RET%"
)
exit /B

Here is a different variant, using cmd /U to convert the string into Unicode, where a null-byte becomers inserted behind every character, and find, which treats these null-bytes like end-of-line markers:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_STRING=Hello world!"

set /A "IDX=0"
for /F delims^=^ eol^= %%I in ('
    cmd /U /V /C echo^(!_STRING!^| find /V ""
') do (
    set "CHR=%%I"
    setlocal EnableDelayedExpansion
    for /F "delims=" %%J in ("$CHR[!IDX!]=!CHR!") do (
        endlocal
        set "%%J"
    )
    set /A "IDX+=1"
)
set $CHR

endlocal
exit /B

Finally, here is another variant, based on a goto loop. This uses a position pointer POS to scan the string and to extract a single character. If no character is returned, the end of the string is reached:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_STRING=Hello world!"

setlocal EnableDelayedExpansion
if not defined _STRING goto :QUIT
set /A "POS=0"
:LOOP
set "CHR=!_STRING:~%POS%,1!"
if defined CHR (
    set "$CHR[%POS%]=!CHR!"
    set /A "POS+=1"
    goto :LOOP
)
:QUIT
set $CHR
endlocal

endlocal
exit /B


来源:https://stackoverflow.com/questions/26576914/windows-batch-split-string-to-individual-characters-to-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!