VB.NET - If string contains “value1” or “value2”

2019-04-17 19:04发布

I'm wondering how I can check if a string contains either "value1" or "value2"? I tried this:

If strMyString.Contains("Something") Then

End if

This works, but this doesn't:

If strMyString.Contains("Something") or ("Something2") Then

End if

This gives me the error that conversion from string to Long can't be done. If I put the or ("Something2") inside the parenthesis of the first one, it gives me the error that the string cannot be converted to Boolean.

So how can I check if the string contains either "string1" or "string2" without having to write too much code?

8条回答
Bombasti
2楼-- · 2019-04-17 19:29

You have ("Something2") by itself - you need to test it so a boolean is returned:

If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
查看更多
ら.Afraid
3楼-- · 2019-04-17 19:34
 If strMyString.Tostring.Contains("Something") or strMyString.Tostring.Contains("Something2") Then


     End if
查看更多
混吃等死
4楼-- · 2019-04-17 19:39

You need this

If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
    'Code
End if
查看更多
ら.Afraid
5楼-- · 2019-04-17 19:40

Interestingly, this solution can break, but a workaround: Looking for my database called KeyWorks.accdb which must exist:

Run this:

Dim strDataPath As String = GetSetting("KeyWorks", "dataPath", "01", "") 'get from registry

If Not strDataPath.Contains("KeyWorks.accdb") Then....etc.

If my database is named KeyWorksBB.accdb, the If statement will find this acceptable and exit the if statement because it did indeed find KeyWorks and accdb.

If I surround the If statement qualifier with single quotes like ("'KeyWorks.accdb'"), it now looks for all the consecutive characters in order and would enter the If block because it did not match.

查看更多
6楼-- · 2019-04-17 19:43
If strMyString.Contains("Something") or strMyString.Contains("Something2") Then

End if

The error indicates that the compiler thinks you want to do a bitwise OR on a Boolean and a string. Which of course won't work.

查看更多
啃猪蹄的小仙女
7楼-- · 2019-04-17 19:48

Here is the alternative solution to check whether a particular string contains some predefined string. It uses IndexOf Function:

'this is your string
Dim strMyString As String = "aaSomethingbb"

'if your string contains these strings
Dim TargetString1 As String = "Something"
Dim TargetString2 As String = "Something2"

If strMyString.IndexOf(TargetString1) <> -1 Or strMyString.IndexOf(TargetString2) <> -1 Then

End If

NOTE: This solution has been tested with Visual Studio 2010.

查看更多
登录 后发表回答