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
Release: 2024-12-31 03:34:15
Original
1085 people have browsed it

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... };
Copy after login

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

if (stringArray.Any(stringToCheck.Contains))
Copy after login

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)))
Copy after login

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))
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template