954,517 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Find string in array

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

shers
Junior Poster
116 posts since Aug 2007
Reputation Points: 8
Solved Threads: 0
 
For Each s As String In Src

Next
Ossehaas
Light Poster
32 posts since Jan 2008
Reputation Points: 10
Solved Threads: 1
 

something that's fast.

shers
Junior Poster
116 posts since Aug 2007
Reputation Points: 8
Solved Threads: 0
 
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 ;)

Teme64
Veteran Poster
1,031 posts since Aug 2008
Reputation Points: 218
Solved Threads: 203
 
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.

fisherpeter
Newbie Poster
1 post since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You