gpt4 book ai didi

arrays - 将函数的第二个参数读入数组

转载 作者:行者123 更新时间:2023-12-02 21:44:07 27 4
gpt4 key购买 nike

我编写了以下代码,它完全按照我想要的方式工作:

@echo off
setlocal enabledelayedexpansion

set /a i=0
set in="This is line 1", "This is line 2"
for %%h in (%in%) do (
set /a i+=1
set "val[!i!]=%%h"
)
set out=
for /l %%n in (1,1,!i!) do (
set out=!out! !val[%%n]! ^& vbcrlf ^& _)
echo !out:~1,-12!

它获取 %in% 变量的值并将每个逗号分隔的行读入数组的一个元素中,然后对其进行一些字符串连接并输出一个新字符串。现在,当我尝试将其转换为函数时,由于 %2 被解析为参数的方式而失败。我需要将 %2 解析为具有可变数量值的单个逗号分隔字符串。这个简单的测试不起作用:

call :Test Title "This is line 1","This is line 2" "arg3"
exit /b

:Test arg1 arg2 arg3
set /a i=0
for %%h in (%2) do (
set /a i+=1
set "val[!i!]=%%h"
)
set out=
for /l %%n in (1,1,!i!) do (
set out=!out! !val[%%n]! ^& vbcrlf ^& _)
echo %1 !out:~1,-12! %3
exit /b

我唯一能想到的是使用 %* 并将分隔符更改为唯一的东西,但如果可能的话我宁愿避免这样做。

最佳答案

1。切换中间参数

这将单独保留 %1 并转移所有中间参数,当没有更多参数时停止并将最后一个参数保留在 %3 中。

@echo off
setlocal
call :Test One "Two","Three" Four
endlocal
exit /b 0

:Test <Title> <Lines...> <LastArg>
echo %2
set "Temp=%4"
if defined Temp shift /2 & goto Test
echo %1
echo %3
exit /b 0

输出

"Two"
"Three"
One
Four

2。将字符串放入变量中并传递变量名称

@echo off
setlocal EnableDelayedExpansion
set "String="Two","Three""
call :Test One String Four
endlocal
exit /b 0

:Test <a> <b> <c>
echo %1
echo !%2!
echo %3
exit /b 0

输出

One
"Two","Three"
Four

这是我首先想到的两个解决方案。

更新

这是使用内部循环应用于代码的移位方法 :__Test

@echo off
setlocal EnableDelayedExpansion
call :Test Title "This is line 1","This is line 2" "arg3"
endlocal
exit /b 0

:Test <arg1> <arg2[,...]> <arg3>
set "i=0"
:__Test
set /a "i+=1"
set "val[!i!]=%2"
set "tempvar=%4"
if defined tempvar shift /2 & goto __Test
set "out="
for /l %%n in (1,1,!i!) do (
set out=!out! !val[%%n]! ^& vbcrlf ^& _)
echo %1 !out:~1,-12! %3
exit /b 0

关于arrays - 将函数的第二个参数读入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19814734/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com