Steve
Steve

Reputation: 20469

VB.net fastest way to check if a string contains 1 of many strings

OK, so i want to check if a large string contains one (any) of many other strings within an array.

I can loop through that array and perform 'if largestring.contains(arrayitem) do something then exit for' but i feel this is probably inefficient especially if the array of strings is very large.

Plus the performance will vary depending on the position in the array of the found string Is there a better way to do this?

Upvotes: 1

Views: 10766

Answers (2)

Pavel P
Pavel P

Reputation: 241

Best Approach I think is to use regular expressions

Imports System.Text.RegularExpressions

Dim arrayitems As New Regex(arrayitem(0) & "|" & arrayitem(1) & "|"  & arrayitem(2))

If arrayitems.IsMatch(largestring) Then 
  'Exists
  '...
End If

Another Alternative is to use IndexOf which (in theory) is marginally faster than Contains

Dim str As String = "Hello World."

' Does the string contain "World"?
If (str.IndexOf("World") <> -1) Then
  Console.Write("string contains 'World'")
Else
  Console.Write("string does not contain 'World'")
End If

Upvotes: 3

aserwin
aserwin

Reputation: 1050

Dim result As String() = Array.FindAll(arr, Function(s) s.Contains("whatever"))

Upvotes: 1

Related Questions