Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search a Substring in String array in C#

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?

like image 859
user3147056 Avatar asked Dec 30 '13 18:12

user3147056


People also ask

How do you check if a substring is in a string in C?

The function strstr returns the first occurrence of a string in another string. This means that strstr can be used to detect whether a string contains another string. In other words, whether a string is a substring of another string.

How do you find a specific substring in a string?

To locate a substring in a string, use the indexOf() method. Let's say the following is our string. String str = "testdemo"; Find a substring 'demo' in a string and get the index.

What does strstr () do in C?

The strstr() function returns a pointer to the beginning of the first occurrence of string2 in string1. If string2 does not appear in string1, the strstr() function returns NULL. If string2 points to a string with zero length, the strstr() function returns string1.


1 Answers

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?

like image 79
Andy_Vulhop Avatar answered Nov 14 '22 20:11

Andy_Vulhop