【问题标题】:How to return an element of an array in Batch?如何批量返回数组的元素?
【发布时间】:2012-05-29 12:52:40
【问题描述】:

我的程序的数组列表中有两个元素。如何将变量分配为等于其中一个元素?

代码如下:

@echo off
setlocal enabledelayedexpansion
set /p string=
for /l %%a in (0,1,1000) do if not "!String:~%%a,1!"=="" set /a length=%%a+1
set i=0
:input
set str=%string:~0,1%
if "%str%"=="M" set array[i]=1000
if "%str%"=="D" set array[i]=500
if "%str%"=="C" set array[i]=100
if "%str%"=="L" set array[i]=50
if "%str%"=="X" set array[i]=10
if "%str%"=="I" set array[i]=1
set string=%string:~1%
set /a i=i+1
if %i%==%length% goto logic
goto input
:logic

我真的认为有一种标准的方法可以做到这一点。

【问题讨论】:

  • 请输入代码,我不知道您的阵列或任何东西是如何设置的。
  • 您使用哪种语言?显示一些代码!

标签: arrays list variables batch-file element


【解决方案1】:

主要问题是您的代码没有创建任何batch-array
您的代码仅创建一个名为 array[i] 的变量,但我想您想创建一个数组:

array[0]=1000
array[1]=500

那么你需要类似的东西

setlocal EnableDelayedExpansion
set i=0
:inputLoop
set "str=%string:~0,1%"
if "%str%"=="M" set array[%i%]=1000
if "%str%"=="D" set array[%i%]=500
if "%str%"=="C" set array[%i%]=100
if "%str%"=="L" set array[%i%]=50
if "%str%"=="X" set array[%i%]=10
if "%str%"=="I" set array[%i%]=1
set "string=%string:~1%"
set /a i+=1
if NOT %i%==%length% goto :inputLoop

:logic
rem ** logic begins
for /L %%n in (1 1 %i%) do (
   echo !array[%%n]!
   set /a value=array[%%n]
)

逻辑部分你可以看到如何访问一个数组元素。

顺便说一句。您的 strlen 函数有点慢,使用二分搜索可能会更快。
How to count the characters in a string with Batch?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 2021-12-11
    相关资源
    最近更新 更多