Hi,

I'm working in VB.Net. I have a textbox in which the user enters a number of strings seperated by comma. I store this value in a string array like this

Dim Src() As String
  Src = txtVals.Text.Split(",".ToCharArray)

I want to search a dynamic string in this array. How could I do it in the fastest way?

Thanks

something that's fast.

How fast is fast? Ok, how many items in an array you're talking about?

Here's a small optimization to code what Ossehaas showed

Dim Src() As String
    Const MyStr As String = "abc"

    If TextBox1.Text.IndexOf(MyStr) < 0 Then
      ' Not found
    Else
      Src = TextBox1.Text.Split(",".ToCharArray)
      ' Ossehaas
      For Each s As String In Src
        If MyStr = s Then
          ' Found
          Exit For
        End If
      Next
    End If

If TextBox1.Text.IndexOf(MyStr) < 0 Then should speed up the worst case scenario i.e. the string does not exist in the array.

Array class has also Find and FindIndex methods. See from the .NET documentation, how they are defined. Then you may look at this article: Edgewaters: Using Predicates with VB.Net Array and List Find methods.

You didn't mention if the order of the items in the array must be maintained. If the order of the items is irrelevant, you can use Array.Sort(Src) and then binary search.

In theory binary search is the fastest method with O(log(n)) while the first methods are O(n2). That's the theory, not the practice ;)

Dim Keys(20000) as string, Key as string
If InStr(Join(Keys, ":"), Key) > 0 Then
                        ' found 
End IF

This seems better to me than trying to process some sort of loop, but it only works for text, of course. AND you have to be sure that the JOIN character(s) will never be in the data, so you could use vbcrlf or similar.

I haven't done any timings though.

Edited 4 Years Ago by fisherpeter: n/a

This article has been dead for over six months. Start a new discussion instead.