Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C# to check if string contains a string in string array

I want to use C# to check if a string value contains a word in a string array. For example,

string stringToCheck = "text1text2text3";  string[] stringArray = { "text1", "someothertext", etc... };  if(stringToCheck.contains stringArray) //one of the items? {  } 

How can I check if the string value for 'stringToCheck' contains a word in the array?

like image 530
Theomax Avatar asked May 26 '10 11:05

Theomax


People also ask

What is using () in C#?

The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.

What is the purpose of using statement?

The using statement is used to set one or more than one resource. These resources are executed and the resource is released. The statement is also used with database operations. The main goal is to manage resources and release all the resources automatically.

Does using statement Call dispose?

The using statement guarantees that the object is disposed in the event an exception is thrown. It's the equivalent of calling dispose in a finally block.

Is Vs as C#?

The is operator returns true if the given object is of the same type, whereas the as operator returns the object when they are compatible with the given type. The is operator returns false if the given object is not of the same type, whereas the as operator returns null if the conversion is not possible.


2 Answers

Here's how:

using System.Linq;  if(stringArray.Any(stringToCheck.Contains))  /* or a bit longer: (stringArray.Any(s => stringToCheck.Contains(s))) */ 

This checks if stringToCheck contains any one of substrings from stringArray. If you want to ensure that it contains all the substrings, change Any to All:

if(stringArray.All(stringToCheck.Contains)) 
like image 81
Anton Gogolev Avatar answered Sep 27 '22 23:09

Anton Gogolev


here is how you can do it:

string stringToCheck = "text1"; string[] stringArray = { "text1", "testtest", "test1test2", "test2text1" }; foreach (string x in stringArray) {     if (stringToCheck.Contains(x))     {         // Process...     } } 

UPDATE: May be you are looking for a better solution.. refer to @Anton Gogolev's answer below which makes use of LINQ.

like image 39
Abdel Raoof Olakara Avatar answered Sep 27 '22 23:09

Abdel Raoof Olakara