Coder Perfect

Check if a string contains a list element (of strings)

Problem

For the following code block:

For I = 0 To listOfStrings.Count - 1
    If myString.Contains(lstOfStrings.Item(I)) Then
        Return True
    End If
Next
Return False

The output is:

Case 1:

myString: C:\Files\myfile.doc
listOfString: C:\Files\, C:\Files2\
Result: True

Case 2:

myString: C:\Files3\myfile.doc
listOfString: C:\Files\, C:\Files2\
Result: False

The list (listOfStrings) may have numerous items (at least 20) and must be compared to thousands of strings (like myString).

Is there a more efficient (better) way of writing this code?

Asked by user57175

Solution #1

Using LINQ and C# (I don’t know much about VB these days):

bool b = listOfStrings.Any(s=>myString.Contains(s));

or (more succinct and efficient, but arguably less clear):

bool b = listOfStrings.Any(myString.Contains);

If you’re looking for a way to test equality, HashSet and the like are useful, but they won’t help with partial matches until you separate it into fragments and add an order of complexity.

If you actually mean “StartsWith,” you might sort the list and put it in an array, then use Array.BinarySearch to find each item, checking by lookup to see if it’s a full or partial match.

Answered by Marc Gravell

Solution #2

It should look like this while you’re creating your strings.

bool inact = new string[] { "SUSPENDARE", "DIZOLVARE" }.Any(s=>stare.Contains(s));

Answered by Simi2525

Solution #3

A previous similar query, “Best technique to test for existing string against a huge list of comparables,” yielded a variety of suggestions.

Regex might be enough to meet your needs. All of the possible substrings would be concatenated, with an OR “|” operator between them in the expression. Naturally, you’ll have to keep an eye out for unescaped characters in the expression, as well as failure to compile it due to complexity or size constraints.

Another option is to create a trie data structure that represents all of the potential substrings (this may somewhat duplicate what the regex matcher is doing). As you go through each character in the test string, a new pointer to the trie’s root is created, and existing pointers to the corresponding child are advanced (if any). When any pointer reaches a leaf, you obtain a match.

Answered by Zach Scrivena

Solution #4

Marc’s response was good, but the Contains matching has to be CaSe InSenSiTiVe.

The answer was simple:

bool b = listOfStrings.Any(s => myString.IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0))

Answered by WhoIsRich

Solution #5

This is an old question. However, because VB.NET was the initial requirement. Using the approved answer’s values as a guide:

listOfStrings.Any(Function(s) myString.Contains(s))

Answered by Luis Lavieri

Post is based on https://stackoverflow.com/questions/500925/check-if-a-string-contains-an-element-from-a-list-of-strings