Lets say we have two input string: STACK is a string to search in and NEEDLE is a string to be looked for. There are three answers.
1. STACK contains NEEDLE
2. STACK starts with NEEDLE
3. STACK ends with NEEDLE
There are explanations below showing possible troubles with them
1. We could say that the following code is responsible for the first answer:
Code: Select all
setlocal enabledelayedexpansion
set "if_stack=%~1"
set "if_needle=%~2"
if not "!if_stack!" == "!if_stack:%if_needle%=!" (
endlocal
exit /b 0
)
endlocal
exit /b 1
It works in the most of cases but we cannot be sure absolutely. It works until we use some special characters in input strings. I have investigated this issue with some of them and found that "=" (equal sign) and "*" (asterisk sign) bring to the issue. See the following examples:
Code: Select all
call if_contains "abc" "b" && echo OK
call if_contains "abc" "=" && echo OK
2. How to test if the string starts with another one we can learn by this link :StartsWith - Tests if a text starts with a given string. Unfortunately, we have the same troubles as described above.
In my opinion the better and the more reliable way is as follows. Estimate the length of NEEDLE. Bit the most beginning or ending part of the same length from STACK and compare it with NEEDLE. The NEEDLE length is calculated by the way as described here :strLen - returns the length of a string. The resulting algorithm is the following:
Code: Select all
setlocal enabledelayedexpansion
set "if_stack=%~1"
set "if_needle=%~2"
rem Estimate the length of the NEEDLE string
set "if_str=A!if_needle!"
set /a "if_len=0"
for /l %%a in ( 12, -1, 0 ) do (
set /a "if_len|=1<<%%a"
for %%b in ( !if_len! ) do if "!if_str:~%%b,1!" == "" set /a "if_len&=~1<<%%a"
)
rem Extract the leading %if_len% characters from the STACK string
call set "if_str=%%if_stack:~0,!if_len!%%"
if "!if_str!" == "!if_needle!" (
endlocal
exit /b 0
)
endlocal
exit /b 1
The same usage examples for the code above
Code: Select all
call if_starts "abc" "ab" && echo OK
call if_starts "abc" "a=" && echo OK
As a conclusion - my questions
Do you know the better solutions for StartsWith/EndsWith?
Do you know the reliable solution for Contains?