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?
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.
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.
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 ).
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[] { ' ', ',', ':' })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With