用通配符比较两个字符串

时间:2016-05-23 15:03:42

标签: vb.net

我想比较两个字符串。我想能够说s1等于s2,因为常用词“hello”。关于如何在有或没有其他功能的情况下实现此目的的任何建议?

s1: hello
s2: hello world

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

2 个答案:

答案 0 :(得分:3)

听起来好像要比较子字符串,可以使用String.Contains

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

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

或(如果你想忽略这种情况)String.IndexOf如果找不到则返回-1:

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

VB.NET中的第三个选项是使用Like运算符(默认情况下也区分大小写):

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

Like-operator支持通配符:

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

答案 1 :(得分:2)

如果您只是在寻找两个字符串是否在其中某处“hello”

If s1.Contains("hello") AndAlso s2.Contains("hello") Then
    'do something
Else
    'do something else
End If