Reputation:
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
Upvotes: 1
Views: 6734
Reputation: 1495
If you're just looking for whether or not both strings have "hello" somewhere in them
If s1.Contains("hello") AndAlso s2.Contains("hello") Then
'do something
Else
'do something else
End If
Upvotes: 2
Reputation: 460098
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
Upvotes: 5