8

I want to be able to effectively search an array for the contents of a string.
Example:

dim arr() as string={"ravi","Kumar","Ravi","Ramesh"}

I pass the value is "ra" and I want it to return the index of 2 and 3.

How can I do this in VB.NET?

5
  • 1
    Shouldn't you get 0,2,3? You're clearly doing a case-insensitive filter. Commented Mar 30, 2009 at 13:50
  • Passing in "ra" would get you 0, 2 and 3. Commented Mar 30, 2009 at 13:50
  • Make your question clearer case sensitive or what?? Commented Mar 30, 2009 at 13:54
  • Which version of VB.NET? Most of the answers seem to be 3.0+. Commented Mar 30, 2009 at 13:58
  • He meant 3.0+ for .NET version. :P Commented May 14, 2009 at 15:41

9 Answers 9

17

It's not exactly clear how you want to search the array. Here are some alternatives:

Find all items containing the exact string "Ra" (returns items 2 and 3):

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

Find all items starting with the exact string "Ra" (returns items 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.StartsWith("Ra"))

Find all items containing any case version of "ra" (returns items 0, 2 and 3):

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

Find all items starting with any case version of "ra" (retuns items 0, 2 and 3):

Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))

-

If you are not using VB 9+ then you don't have anonymous functions, so you have to create a named function.

Example:

Function ContainsRa(s As String) As Boolean
   Return s.Contains("Ra")
End Function

Usage:

Dim result As String() = Array.FindAll(arr, ContainsRa)

Having a function that only can compare to a specific string isn't always very useful, so to be able to specify a string to compare to you would have to put it in a class to have somewhere to store the string:

Public Class ArrayComparer

   Private _compareTo As String

   Public Sub New(compareTo As String)
      _compareTo = compareTo
   End Sub

   Function Contains(s As String) As Boolean
      Return s.Contains(_compareTo)
   End Function

   Function StartsWith(s As String) As Boolean
      Return s.StartsWith(_compareTo)
   End Function

End Class

Usage:

Dim result As String() = Array.FindAll(arr, New ArrayComparer("Ra").Contains)
Sign up to request clarification or add additional context in comments.

1 Comment

I think he was looking for the index
3
Dim inputString As String = "ra"
Enumerable.Range(0, arr.Length).Where(Function(x) arr(x).ToLower().Contains(inputString.ToLower()))

1 Comment

Corrected. I confused the parameter x with inputString
2

If you want an efficient search that is often repeated, first sort the array (Array.Sort) and then use Array.BinarySearch.

Comments

2

In case you were looking for an older version of .NET then use:

Module Module1

    Sub Main()
        Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
        Dim result As New List(Of Integer)
        For i As Integer = 0 To arr.Length
            If arr(i).Contains("ra") Then result.Add(i)
        Next
    End Sub

End Module

2 Comments

Don't forget ToLower... the algorithm as written would not return 2 and 3, only 0.
That's his choice As well as Contains or ForEach; He didn't really say if he wants his check to ignore case, or if he wants his query to be "StartsWith" or "Contains" function, that's his choice. Look on previous post.
2

check this..

        string[] strArray = { "ABC", "BCD", "CDE", "DEF", "EFG", "FGH", "GHI" };
        Array.IndexOf(strArray, "C"); // not found, returns -1
        Array.IndexOf(strArray, "CDE"); // found, returns index

Comments

1

compare properties in the array if one matches the input then set something to the value of the loops current position, which is also the index of the current looked up item.

simple eg.

dim x,y,z as integer
dim aNames, aIndexes as array
dim sFind as string
for x = 1 to length(aNames)

    if aNames(x) = sFind then y = x

y is then the index of the item in the array, then loop could be used to store these in an array also so instead of the above you would have:

z = 1
for x = 1 to length(aNames)
    if aNames(x) = sFind then 
        aIndexes(z) = x 
        z = z + 1
    endif

Comments

0

VB

Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim result = arr.Where(Function(a) a.Contains("ra")).Select(Function(s) Array.IndexOf(arr, s)).ToArray()

C#

string[] arr = { "ravi", "Kumar", "Ravi", "Ramesh" };
var result = arr.Where(a => a.Contains("Ra")).Select(a => Array.IndexOf(arr, a)).ToArray();

-----Detailed------

Module Module1

    Sub Main()
        Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
        Dim searchStr = "ra"
        'Not case sensitive - checks if item starts with searchStr
        Dim result1 = arr.Where(Function(a) a.ToLower.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
        'Case sensitive - checks if item starts with searchStr
        Dim result2 = arr.Where(Function(a) a.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
        'Not case sensitive - checks if item contains searchStr
        Dim result3 = arr.Where(Function(a) a.ToLower.Contains(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
        Stop
    End Sub

End Module

6 Comments

That scales badly, as it will loop through the array one extra time for each match found.
The problem is that he wants the index, he doesn't want the values.
There is no property Index in an array child. It's actually a good idea, all the items in an array should have a property Array to access the array and Index to have the index of this item in the array...
Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra")) I have used your code in VB.NET 2005 but i am getting error in Function keyword. It is not accepting, please help
I posted another code which is applicaple in .NET 2.0, the previous code was for 3.0+ (maybe only 3.5 donno, but not for 3.0).
|
0

Never use .ToLower and .ToUpper.

I just had problems in Turkey where there are 4 "i" letters. When using ToUpper I got the wrong "Ì" one and it fails.

Use invariant string comparisons: Const LNK as String = "LINK" Dim myString = "Link"

Bad: If myString.ToUpper = LNK Then...

Good and works in the entire world: If String.Equals(myString, LNK , StringComparison.InvariantCultureIgnoreCase) Then...

Comments

-1

This would do the trick, returning the values at indeces 0, 2 and 3.

Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))

4 Comments

This won't return the indices but the actual elements, which is not the OP specifies.
Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra")) I have used your code in VB.NET 2005 but i am getting error in Function keyword. It is not accepting, please help
Dim result2 = arr.Where(Function(a) a.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
This code would only work in VB 9.0+ (i.e. Visual Studio 2008). You should always specify which version you are using in your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.