drgmak
drgmak

Reputation: 1215

Get the whole string from a String array if the string contains a substring

I have a string array for example:

string[] myStrings = {"I want to take this string","This is not interesting"}

I want to check the string array if it contains a value and then return the entire string that contains it.

Example:

var index = Array.FindIndex(stringArray, x => x == stringArray.Contains("want"));

After this I want to return the string: I want to take this string since this contains the keyword I searched for.

How can I archieve this result?

Upvotes: 1

Views: 717

Answers (4)

Avinash
Avinash

Reputation: 11

public string GetStringContent()
{
    string[] myStrings = { "I want to take this string", "This is not interesting" };
    string strContent=string.Empty;
    for (int i = 0; i < myStrings.Length; i++)
    {
        if (myStrings[i].Contains("want"))
        {
           return  myStrings[i];
        }
    }
    return strContent;
} 

Try This... It will return first string if it contains 'want'.

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 156948

I would use LINQ instead:

IEnumerable<string> occurences = stringArray.Where(s => s.Contains("want"));

In occurences you have the complete strings of all occurences which did match. You can do FirstOrDefault on it if you are just interested in the first hit.

Upvotes: 10

Tim Schmelter
Tim Schmelter

Reputation: 460068

You can also use Array.FindIndex as you've already tried, but then use this:

int index = Array.FindIndex(myStrings, str => str.Contains("want"));
string desired = index >= 0 ? myStrings[index] : null; 

Upvotes: 3

Nasreddine
Nasreddine

Reputation: 37798

Try this:

myStrings.FirstOrDefault(str => str.Contains("want"));

This will return the first string that contains want or null if it was not found. If you want a List of all the strings that contain want then replace FirstOrDefault with Where

Upvotes: 2

Related Questions