How to search a Substring in String array in C#

Viewed 15463

How to search for a Substring in String array? I need to search for a Substring in the string array. The string can be located in any part of the array (element) or within an element. (middle of a string) I have tried : Array.IndexOf(arrayStrings,searchItem) but searchItem has to be the EXACT match to be found in arrayStrings. In my case searchItem is a portion of a complete element in arrayStrings.

string [] arrayStrings = {
   "Welcome to SanJose",
   "Welcome to San Fancisco","Welcome to New York", 
   "Welcome to Orlando", "Welcome to San Martin",
   "This string has Welcome to San in the middle of it" 
};
lineVar = "Welcome to San"
int index1 = 
   Array.IndexOf(arrayStrings, lineVar, 0, arrayStrings.Length);
// index1 mostly has a value of -1; string not found

I need to check whether lineVar variable is present in arrayStrings. lineVar can be of different length and value.

What would be the best way to find this substring within an array string?

4 Answers

To find the substrings in the String array using C#

    List<string> searchitem = new List<string>();
    string[] arrayStrings = {
       "Welcome to SanJose",
       "Welcome to San Fancisco","Welcome to New York",
       "Welcome to Orlando", "Welcome to San Martin",
       "This string has Welcome to San in the middle of it"
    };
   string searchkey = "Welcome to San";
   for (int i = 0; i < arrayStrings.Length; i++)
   {
    if (arrayStrings[i].Contains(searchkey))//checking whether the searchkey contains in the string array
    {
     searchitem.Add(arrayStrings[i]);//adding the matching item to the list 
    }
   string searchresult = string.Join(Environment.NewLine, searchitem);

Output for Searchresult:

Welcome to SanJose

Welcome to San Fancisco

Welcome to San Martin

This string has Welcome to San in the middle of it

Related