Windows批处理中的LastIndexOf

Dan*_*lba 5 windows cmd batch-file

我需要在Windows批处理脚本中实现一个函数,以将LastIndexOf字符放入给定的字符串中.

例如:给定以下字符串,我需要获取最后一个字符索引'/':

/name1/name2/name3
            ^
Run Code Online (Sandbox Code Playgroud)

所以我需要获得价值:

12
Run Code Online (Sandbox Code Playgroud)

dbe*_*ham 8

Joey的解决方案有效,但要查找的字符是硬编码的,而且相对较慢.

这是一个快速的参数化函数,可以在字符串中找到任何字符(除了nul).我传递包含字符串和字符而不是字符串文字的变量名称,以便该函数可以轻松支持所有字符.

@echo off
setlocal

set "test=/name1/name2/name3"
set "char=/"

::1st test simply prints the result
call :lastIndexOf test char

::2nd test stores the result in a variable
call :lastIndexOf test char rtn
echo rtn=%rtn%

exit /b

:lastIndexOf  strVar  charVar  [rtnVar]
  setlocal enableDelayedExpansion

  :: Get the string values
  set "lastIndexOf.char=!%~2!"
  set "str=!%~1!"
  set "chr=!lastIndexOf.char:~0,1!"

  :: Determine the length of str - adapted from function found at:
  :: http://www.dostips.com/DtCodeCmdLib.php#Function.strLen
  set "str2=.!str!"
  set "len=0"
  for /L %%A in (12,-1,0) do (
    set /a "len|=1<<%%A"
    for %%B in (!len!) do if "!str2:~%%B,1!"=="" set /a "len&=~1<<%%A"
  )

  :: Find the last occurrance of chr in str
  for /l %%N in (%len% -1 0) do if "!str:~%%N,1!" equ "!chr!" (
    set rtn=%%N
    goto :break
  )
  set rtn=-1

  :break - Return the result if 3rd arg specified, else print the result
  ( endlocal
    if "%~3" neq "" (set %~3=%rtn%) else echo %rtn%
  )
exit /b
Run Code Online (Sandbox Code Playgroud)

创建一个更通用的:indexOf函数并不需要太多修改,该函数需要一个额外的参数来指定要查找的出现次数.负数可以指定反向搜索.所以1可以是第1,第2,第2,-1,最后,-2倒数第二,等等.


Joe*_*oey 6

(注意:我假设Windows批处理文件,因为,坦白说,到目前为止,我只看到一个问题要求实际的DOS批处理文件.大多数人只是将"DOS"错误地归因于任何有灰色窗口的东西.黑色等宽文本,不知道他们实际在谈论什么.)

只需循环遍历它,随时更新索引:

@echo off
setlocal enabledelayedexpansion
set S=/name1/name2/name3
set I=0
set L=-1
:l
if "!S:~%I%,1!"=="" goto ld
if "!S:~%I%,1!"=="/" set L=%I%
set /a I+=1
goto l
:ld
echo %L%
Run Code Online (Sandbox Code Playgroud)