hey all,
can someone please show me how to search my String[] array to see if an
element "contains" a certain string constant and then return the index value
of the found element?
thanks,
rodchar
Peter Morris - 24 Mar 2008 16:52 GMT
public int IndexOfSubString(string[] values, string value)
{
for (int index = 0; index < values.Length; index++)
if (values[index].IndexOf(value) > -1)
return index;
return -1;
}
Jon Skeet [C# MVP] - 24 Mar 2008 16:55 GMT
> can someone please show me how to search my String[] array to see if an
> element "contains" a certain string constant and then return the index value
> of the found element?
See Array.IndexOf.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Jon Skeet [C# MVP] - 24 Mar 2008 17:18 GMT
> > can someone please show me how to search my String[] array to see if an
> > element "contains" a certain string constant and then return the index value
> > of the found element?
>
> See Array.IndexOf.
Whoops - apologies for this, I didn't read the question quite carefully
enough :(

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Arne Vajhøj - 25 Mar 2008 02:31 GMT
>>> can someone please show me how to search my String[] array to see if an
>>> element "contains" a certain string constant and then return the index value
[quoted text clipped - 3 lines]
> Whoops - apologies for this, I didn't read the question quite carefully
> enough :(
It is actually pretty close.
With latest and greatest:
Array.FindIndex(strarr, (string strelm) => strelm.Contains(fndstr))
Arne
rodchar - 24 Mar 2008 17:05 GMT
Thanks for the help,
rod.
> hey all,
> can someone please show me how to search my String[] array to see if an
[quoted text clipped - 3 lines]
> thanks,
> rodchar
Gilles Kohl [MVP] - 24 Mar 2008 17:06 GMT
>hey all,
>can someone please show me how to search my String[] array to see if an
>element "contains" a certain string constant and then return the index value
>of the found element?
Here's something straightforward:
static int FindStringContainingText(string[] strings, string textToFind)
{
for(int i = 0; i < strings.Length; i++)
{
if(strings[i].Contains(textToFind))
{
return i;
}
}
return -1;
}
Returns the index of the string containing the text you're looking for, or -1
if not found.
call e.g. like so:
int foundPosition = FindStringContainingText(theArray, "42");
With C# 3.0, you could also use LINQ:
foundPosition = Enumerable.Range(0, theArray.Length).First(i =>
theArray[i].Contains("42"));
Regards,
Gilles.