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
Old school:
int index = -1;
for(int i = 0; i < arrayStrings.Length; i++){
if(arrayStrings[i].Contains(lineVar)){
index = i;
break;
}
}
If you need all the indexes:
List<Tuple<int, int>> indexes = new List<Tuple<int, int>>();
for(int i = 0; i < arrayStrings.Length; i++){
int index = arrayStrings[i].IndexOf(lineVar);
if(index != -1)
indexes.Add(new Tuple<int, int>(i, index)); //where "i" is the index of the string, while "index" is the index of the substring
}
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
If all you need is a bool true/false answer as to whether the lineVar
exists in any of the strings in the array, use this:
arrayStrings.Any(s => s.Contains(lineVar));
If you need an index, that's a bit trickier, as it can occur in multiple items of the array. If you aren't looking for a bool, can you explain what you need?
If you need the Index of the first element that contains the substring in the array elements, you can do this...
int index = Array.FindIndex(arrayStrings, s => s.StartsWith(lineVar, StringComparison.OrdinalIgnoreCase)) // Use 'Ordinal' if you want to use the Case Checking.
If you need the element's value that contains the substring, just use the array with the index you just got, like this...
string fullString = arrayStrings[index];
Note: The above code will find the first occurrence of the match. Similary, you can use Array.FindLastIndex() method if you want the last element in the array that contains the substring.
You will need to convert the array to a List<string>
and then use the ForEach
extension method along with Lambda expressions to get each element that contains the substring.