Help Man Help Man - 6 months ago 19
Vb.net Question

Compare two strings with wildcard

I want to compare two strings. I want to be able to say that s1 is equal to s2 because of the common word "hello". any suggestions on how to achieve this with or without another function?

s1: hello
s2: hello world

if s1 = s2 then
..do something
else
..do something
end if

Answer

It sounds as if you want to compare substrings, you can use String.Contains:

Dim s1 = "hello"
Dim s2 = "hello world"

Dim s2ContainsHello As Boolean = s2.Contains(s1) ' True

or (if you want to ignore the case) String.IndexOf which returns -1 if it wasn't found:

s2 = "Hello World"
s2ContainsHello = s2.IndexOf(s1, StringComparison.InvariantCultureIgnoreCase) >= 0 ' Still True

a third option in VB.NET is to use the Like operator (which also is case-sensitive by default):

s2ContainsHello = s2 like "*" & s1 & "*"

The Like-operator supports wild-cards:

Characters in pattern    Matches in string
?                        Any single character
*                        Zero or more characters
#                        Any single digit (0–9)
[charlist]               Any single character in charlist
[!charlist]              Any single character not in charlist