Do you know all about SearchStr? I did not!
To determine if two strings are equal, I always use the If statement in a VisualNeo app. However, there is an interesting alternative.
Let’s compare the first n characters of two strings.
Given: two strings
SetVar "[s1]" "abcdef" SetVar "[s2]" "Abcxyz"
Select the first three characters from [s1] and [s2]
SubStr "[s1]" "1" "3" "[s1-extract]" SubStr "[s2]" "1" "3" "[s2-extract]"
-> [s1] = abc
-> [s2] = Abc
Are these substrings equal?
If "[s1-extract]" "=" "[s2-extract]" SetVar "[mc-return-value]" "1" Else SetVar "[mc-return-value]" "0" EndIf
-> [mc-return-value] = 1
The previous If statement performs a case-insensitive comparison.
For a case-sensitive comparison using the if statement, add ! to one variable
If "[s1-extract]" "=" "![s2-extract]" SetVar "[mc-return-value]" "1" Else SetVar "[mc-return-value]" "0" EndIf
-> [mc-return-value] = 0
The shorter VisualNeo Win alternative is SearchStr when comparing two strings, having the same number of characters
SearchStr "[s1-extract]" "[s2-extract]" "[mc-return-value]" ""
-> [mc-return-value] = 1 due to the case-insensitive comparison
SearchStr "[s1-extract]" "[s2-extract]" "[mc-return-value]" "casesensitive"
-> [mc-return-value] = 0 due to the case-sensitive comparison
Why using SearchStr instead of If when comparing two strings, having the same number of characters?
- Shorter code, i.e. an one-liner
- Faster performance: in a 10000 iteration loop, SearchStr appears -approximately- to be twice as fast as If.
Apart from the one-liner or speed argument, one has to realize that the return variable in SearchStr always has a value: the value 0 (no match) or a value above 0 (match). No separate SetVar “[mc-return-value]” assignments are necessary.
It can be assumed SearchStr can be used successfully in other situations as well. Taking it a step further, two examples:
Example 1:
[mc-checkbox] is a dichotomous variable and has the value ‘checked’ or ” (empty).
Instead of
If "[mc-checkbox]" "=" "checked" SetVar "[mc-return-value]" "1" Else SetVar "[mc-return-value]" "0" EndIf
use
SearchStr "checked" "[mc-checkbox]" "[mc-return-value]" ""
Example 2:
Check if a character is equal to 2, 3, 4, 5, 6, or 7.
Instead of
IfEx "[mc-character] = 2 OR [mc-character] = 3 OR [mc-character] = 4 OR [mc-character] = 5 OR [mc-character] = 6 OR [mc-character] = 7" SetVar "[mc-return-value]" "1" Else SetVar "[mc-return-value]" "0" EndIf
use
SearchStr "[mc-character]" "234567" "[mc-return-value]" ""
Testing speed with a 10000 iteration loop, SearchStr is in both examples the winner!
For all of you, a happy and healthy 2019. And for Luis and his staff, a successful VisualNeo year 2019 also!
Reinier
Comments