search my String[]

  • Thread starter Thread starter rodchar
  • Start date Start date
R

rodchar

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
 
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;
}
 
rodchar said:
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.
 
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.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.Contains("42"));

Regards,
Gilles.
 
Jon Skeet said:
rodchar said:
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 :(
 
Jon said:
Jon Skeet said:
rodchar said:
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 :(

It is actually pretty close.

With latest and greatest:

Array.FindIndex(strarr, (string strelm) => strelm.Contains(fndstr))

Arne
 
Back
Top