Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Windows 如何批量获取子字符串在字符串中的位置_Windows_For Loop_Batch File_Cmd - Fatal编程技术网

Windows 如何批量获取子字符串在字符串中的位置

Windows 如何批量获取子字符串在字符串中的位置,windows,for-loop,batch-file,cmd,Windows,For Loop,Batch File,Cmd,获取子字符串的位置 Set str1=This is Test string Set sstr=Test 这里我需要得到“Test”(8)的位置 谢谢…试试这个: @echo off &setlocal enabledelayedexpansion Set "str1=This is Test string" Set "sstr=Test" call :strlen str1 len1 call :strlen sstr len2 set /a stop=len1-len2 i

获取子字符串的位置

  Set str1=This is Test string
  Set sstr=Test
这里我需要得到“Test”(8)的位置

谢谢…

试试这个:

@echo off &setlocal enabledelayedexpansion
Set "str1=This is Test string"
Set "sstr=Test"
call :strlen str1 len1
call :strlen sstr len2
set /a stop=len1-len2
if %stop% gtr 0 for /l %%i in (0,1,%stop%) do if "!str1:~%%i,%len2%!"=="%sstr%" set /a position=%%i
if defined position (echo.Position of %sstr% is %position%) else echo."%sstr%" not found in "%str1%"
goto :eof

:strlen
:: list string length up to 8189 (and reports 8189 for any string longer than 8189
:: function from http://ss64.org/viewtopic.php?pid=6478#p6478
(   setlocal enabledelayedexpansion & set /a "}=0"
    if "%~1" neq "" if defined %~1 (
        for %%# in (4096 2048 1024 512 256 128 64 32 16) do (
            if "!%~1:~%%#,1!" neq "" set "%~1=!%~1:~%%#!" & set /a "}+=%%#"
        )
        set "%~1=!%~1!0FEDCBA9876543211" & set /a "}+=0x!%~1:~32,1!!%~1:~16,1!"
    )
)
endlocal & set /a "%~2=%}%" & exit /b
endlocal
如果%str1%包含多个%sstr%,代码将找到最后一个位置

@echo OFF
SETLOCAL
Set "str1=This is Test string"
Set "sstr=Test"
SET stemp=%str1%&SET pos=0
:loop
SET /a pos+=1
echo %stemp%|FINDSTR /b /c:"%sstr%" >NUL
IF ERRORLEVEL 1 (
SET stemp=%stemp:~1%
IF DEFINED stemp GOTO loop
SET pos=0
)

ECHO Pos of "%sstr%" IN "%str1%" = %pos%

(这将返回“9”,将第一个位置计算为“1”。定义在用户的脑海中…

和一个额外的备选方案:

@echo off &setlocal enabledelayedexpansion
Set "str1=This is Test string"
Set "sstr=Test"
set /a position=0
Set "sst0=!str1:*%sstr%=!"
if "%sst0%"=="%str1%" echo "%sstr%" not found in "%str1%"&goto :eof
Set "sst1=!str1:%sstr%%sst0%=!"
if "%sst1%" neq "" for /l %%i in (0,1,8189) do if "!sst1:~%%i,1!" neq "" set /a position+=1
echo.Position of %sstr% is %position%
endlocal
如果%str1%包含多个%sstr%,代码将找到第一个位置

@echo OFF
SETLOCAL
Set "str1=This is Test string"
Set "sstr=Test"
SET stemp=%str1%&SET pos=0
:loop
SET /a pos+=1
echo %stemp%|FINDSTR /b /c:"%sstr%" >NUL
IF ERRORLEVEL 1 (
SET stemp=%stemp:~1%
IF DEFINED stemp GOTO loop
SET pos=0
)

ECHO Pos of "%sstr%" IN "%str1%" = %pos%