Home >Backend Development >C++ >How Can I Efficiently Check if a String Contains Any or All Substrings from an Array in C#?

How Can I Efficiently Check if a String Contains Any or All Substrings from an Array in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-31 03:34:151054browse

How Can I Efficiently Check if a String Contains Any or All Substrings from an Array in C#?

Finding Substrings in Strings with C#

In C#, you can efficiently ascertain whether a string contains any substring from a specified string array. Let's consider an example:

string stringToCheck = "text1text2text3";
string[] stringArray = { "text1", "someothertext", etc... };

To check if stringToCheck contains any substring from stringArray, you can employ the following technique:

if (stringArray.Any(stringToCheck.Contains))

This expression uses the LINQ (Language Integrated Query) extension method Any to check whether any of the elements in stringArray are also present as substrings in stringToCheck.

Alternatively, a longer but clearer version of the above code would be:

if (stringArray.Any(s => stringToCheck.Contains(s)))

For a more stringent check, you can use the All method to ensure that stringToCheck contains all substrings from stringArray:

if (stringArray.All(stringToCheck.Contains))

This method will return true only if stringToCheck contains every substring from stringArray. By utilizing these techniques, you can effectively determine whether a string contains any or all substrings from a predefined string array.

The above is the detailed content of How Can I Efficiently Check if a String Contains Any or All Substrings from an Array in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn