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

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

Mary-Kate Olsen
Release: 2025-01-04 15:44:40
Original
476 people have browsed it

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

Verifying String Containment Within an Array Using C#

In C#, you can verify whether a string contains any word from a given string array efficiently. Consider the following scenario:

string stringToCheck = "text1text2text3";

string[] stringArray = { "text1", "someothertext", etc... };
Copy after login

Your goal is to determine if stringToCheck contains any substring present within stringArray.

Solution:

To accomplish this task, utilize the Any method from the System.Linq namespace:

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

This code snippet iterates through each element s in stringArray and calls stringToCheck.Contains(s) to check if stringToCheck contains s. If any of these checks return true, the Any method returns true, indicating that stringToCheck contains at least one substring from the array.

Alternative:

If you want to check if stringToCheck contains all the substrings in stringArray, simply replace Any with All:

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

This ensures that stringToCheck contains every substring present in the array.

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

source:php.cn
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