Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a string contains any items of an List of strings?

Tags:

I have a string and a List of strings:

string motherString = "John Jake Timmy Martha Stewart";

and I want to find if that string contains any of the strings in a list ie:

var children = new List<string>{"John", "Mike", "Frank"};

So I want to find out if motherString contains one of the items from children ie. 'John'

What would be the best way of going about this?

like image 658
Coder 2 Avatar asked Feb 14 '11 00:02

Coder 2


People also ask

How do you check if a string contains a list of strings?

To check if string contains substring from a list of strings, iterate over list of strings, and for each item in the list, check if the item is present in the given string. a source string, in which we have to check if some substring is present.

How do you check if any element of a list is in a string?

Use the filter() Function to Get a Specific String in a Python List. The filter() function filters the given iterable with the help of a function that checks whether each element satisfies some condition or not. It returns an iterator that applies the check for each of the elements in the iterable.

How do you check if a list of strings contains a string in Python?

The easiest way to check if a Python string contains a substring is to use the in operator. The in operator is used to check data structures for membership in Python. It returns a Boolean (either True or False ).


1 Answers

The simplest code I could come up with would be:

var hasAny = children.Any(motherString.Contains);

If you expect each of the words to be seperated by a space then you could use this:

var hasAny = motherString.Split(new[] { ' ' }).Any(children.Contains);

If the words in motherString could be seperated by other characters, you could add them like this:

motherString.Split(new[] { ' ', ',', ':' })
like image 106
Luke Baulch Avatar answered Nov 03 '22 12:11

Luke Baulch