Connecting Tech Pros Worldwide Help | Site Map

How to determine if a string in an array

ad
Guest
 
Posts: n/a
#1: Mar 9 '06
I have a string array.
How can I determine if a string in it?


Larry Lard
Guest
 
Posts: n/a
#2: Mar 9 '06

re: How to determine if a string in an array



ad wrote:[color=blue]
> I have a string array.
> How can I determine if a string in it?[/color]

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 :)

--
Larry Lard
Replies to group pleas

Larry Lard
Guest
 
Posts: n/a
#3: Mar 9 '06

re: How to determine if a string in an array



Larry Lard wrote:[color=blue]
> ad wrote:[color=green]
> > I have a string array.
> > How can I determine if a string in it?[/color]
>
> Arrays implement IList, which has a Contains method.
>
> New VB.NET Console app:[/color]

Oops. Too many ngs today. But you get my point, I'm sure.

--
Larry Lard
Replies to group please

Jon Skeet [C# MVP]
Guest
 
Posts: n/a
#4: Mar 9 '06

re: How to determine if a string in an array


ad wrote:[color=blue]
> I have a string array.
> How can I determine if a string in it?[/color]

Just to rewrite Larry's code in C#:

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

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

Jon

Stoitcho Goutsev \(100\)
Guest
 
Posts: n/a
#5: Mar 9 '06

re: How to determine if a string in an array


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 [C# MVP]" <skeet@pobox.com> wrote in message
news:1141914399.032720.79110@p10g2000cwp.googlegro ups.com...[color=blue]
> ad wrote:[color=green]
>> I have a string array.
>> How can I determine if a string in it?[/color]
>
> Just to rewrite Larry's code in C#:
>
> string[] x = new string[] {"apple", "banana", "pear"};
>
> if ( ((IList)x).Contains ("apple"))
> {
> ...
> }
>
> Jon
>[/color]


Closed Thread