How to determine if a string in an array

  • Thread starter Thread starter ad
  • Start date Start date
ad said:
I have a string array.
How can I determine if a string in it?

Arrays implement IList, which has a Contains method.

New VB.NET Console app:

Module Module1

Sub Main()
Dim ss() As String = New String() {"apple", "banana", "grape"}

If ArrayContainsString(ss, "banana") Then
Console.WriteLine("Array contains banana")
Else
Console.WriteLine("Array does not contain banana")
End If

If ArrayContainsString(ss, "pear") Then
Console.WriteLine("Array contains pear")
Else
Console.WriteLine("Array does not contain pear")
End If

Console.ReadLine()
End Sub

Function ArrayContainsString(ByVal a As Array, ByVal s As String)
As Boolean
Dim l As IList = a
Return l.Contains(s)
End Function
End Module

Don't ask me about case/accent sensitivity :)
 
ad said:
I have a string array.
How can I determine if a string in it?

Just to rewrite Larry's code in C#:

string[] x = new string[] {"apple", "banana", "pear"};

if ( ((IList)x).Contains ("apple"))
{
...
}

Jon
 
Hi,

Just a little something here...

All methods that can be used such as IndexOf, LastIndexOf or Contains
whether instace or static work for one-dimensional arrays only. For
multy-dimensional arrays I'm afraid custom search needs to be implemented.


--

Stoitcho Goutsev (100)

Jon Skeet said:
ad said:
I have a string array.
How can I determine if a string in it?

Just to rewrite Larry's code in C#:

string[] x = new string[] {"apple", "banana", "pear"};

if ( ((IList)x).Contains ("apple"))
{
...
}

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top