Code: Select all
@echo off
Cls
Set /p input="enter a word "
::Search for character
Set before=
Set char=
Set after=
Moderator: DosItHelp
Code: Select all
@echo off
Cls
Set /p input="enter a word "
::Search for character
Set before=
Set char=
Set after=
Code: Select all
Set before= th
Set char=e
Set after=re
Code: Select all
REM Subroutine to locate a string within another string and return the 0 based offset (-1 indicates not found)
:Instr [target-string] [search-string] [loc-var]
set "%~3=-1" & set "_str1=%~1"
call :StrLen "%~1" _len1 & call :StrLen "%~2" _len2 & set /A "_chk=_len1-_len2"
for %%A in (!_len2!) do (for /L %%B in (0,1,!_chk!) do (if /I "%~2" == "!_str1:~%%B,%%A!" (set "%~3=%%B" & exit /b)))
exit /b
REM Subroutine to return the length of a string variable
:StrLen [string] [len-var]
set "_str=A%~1" & set "_len=0"
for /L %%A in (12,-1,0) do (set /a "_len|=1<<%%A" & for %%B in (!_len!) do if "!_str:~%%B,1!"=="" set /a "_len&=~1<<%%A")
set /a %~2=%_len%
exit /b
Code: Select all
call :InStr "there" "e" Loc
batchcc wrote:Every time I try this code even when the input has no "e" the variable %loc% echos -1
Code: Select all
@echo off
cls
call :InStr "there" "e" Loc
echo %loc%
pause
REM Subroutine to locate a string within another string and return the 0 based offset (-1 indicates not found)
:Instr [target-string] [search-string] [loc-var]
set "%~3=-1" & set "_str1=%~1"
call :StrLen "%~1" _len1 & call :StrLen "%~2" _len2 & set /A "_chk=_len1-_len2"
for %%A in (!_len2!) do (for /L %%B in (0,1,!_chk!) do (if /I "%~2" == "!_str1:~%%B,%%A!" (set "%~3=%%B" & exit /b)))
exit /b
REM Subroutine to return the length of a string variable
:StrLen [string] [len-var]
set "_str=A%~1" & set "_len=0"
for /L %%A in (12,-1,0) do (set /a "_len|=1<<%%A" & for %%B in (!_len!) do if "!_str:~%%B,1!"=="" set /a "_len&=~1<<%%A")
set /a %~2=%_len%
exit /b
Code: Select all
@echo off
Cls
Set /p input="enter a word "
::Search for character "e"
Set "char=e"
for /F "tokens=1* delims=%char%" %%a in ("%input%") do (
Set "before=%%a"
Set "after=%%b"
)
echo Before: "%before%"
echo Char: "%char%"
echo After: "%after%"
batchcc wrote:Thanks Aacini and Squashman, Aacini's code worked but just for my reference in the future if I wanted to ignore the first "e" and use the second occurrence of the letter "e" is there an easy way to do this as well? Thanks
Code: Select all
@echo off
Cls
Set "input=therefore"
::Search for character "e"
Set "char=e"
for /F "tokens=1,2* delims=%char%" %%a in ("%input%") do (
Set "part1=%%a"
Set "part2=%%b"
set "part3=%%c
)
echo Before: "%part1%%char%%part2%"
echo Char: "%char%"
echo After: "%part3%"
pause
Code: Select all
Before: "ther"
Char: "e"
After: "fore"
Press any key to continue . . .