How to find a substring in a String array in C #

How to find a substring in a String array? I need to find a substring in an array of strings. The string can be located in any part of the array (element) or inside the element. (middle of line) I tried: Array.IndexOf(arrayStrings,searchItem)but searchItem should be an EXACT match that can be found in arrayStrings. In my case, searchItem is part of the 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 if the lineVar variable is present in arrayStrings. lineVar can have different lengths and meanings.

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

+4
source share
3 answers

bool true/false , lineVar , :

 arrayStrings.Any(s => s.Contains(lineVar));

, , . bool, , ?

+9

:

int index = -1;

for(int i = 0; i < arrayStrings.Length; i++){
   if(arrayStrings[i].Contains(lineVar)){
      index = i;
      break;
   }
}

:

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
}
+1

, , ...

int index = Array.FindIndex(arrayStrings, s => s.StartsWith(lineVar, StringComparison.OrdinalIgnoreCase)) // Use 'Ordinal' if you want to use the Case Checking.

, , , , ...

string fullString = arrayStrings[index];

. . Similary, Array.FindLastIndex(), , .

You will need to convert the array to List<string>, and then use the extension method ForEachalong with the Lambda expressions to get each element containing the substring.

0
source

All Articles