search my String[]

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
 
P

Peter Morris

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;
}
 
J

Jon Skeet [C# MVP]

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.
 
G

Gilles Kohl [MVP]

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.
 
J

Jon Skeet [C# MVP]

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 :(
 
A

Arne Vajhøj

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
 

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

Similar Threads

enum basics 7
search my DataColumn object 1
string array search 7
Configuration Section 3
Problem with ArrayList 4
delimited string test 3
alternative way to validate 4
replacing characters in a string 8

Top