Using C# to Check If String Contains a String in String Array

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

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...
}
}

Maybe you are looking for a better solution... Refer to Anton Gogolev's answer which makes use of LINQ.

Check if a string contains a specific string using array

You probably want case insensitive validation:

string[] badWordArray = { "aBadword1", "aBadWord2", "aBadWord3" };

Boolean isBadWord = badWordArray
.Any(badWord => name.IndexOf(badword, StringComparison.OrdinalIgnoreCase) >= 0);

Or if you verify on current culture

Boolean isBadWord = badWordArray
.Any(badWord => name.IndexOf(badWord, StringComparison.CurrentCultureIgnoreCase) >= 0);

Paranoic case involves using regular expressions like this:

   string[] badWordArray = { "aBadword1", "aBadWord2", "aBadWord3" };

// Nasty user wants to be rude but pass typical filters...
String name = "A- Bad..WORD..1 !!!";

String line = Regex.Replace(name, @"\W", "");

Boolean isBadWord = badWordArray
.Any(badWord => line.IndexOf(badWord, StringComparison.OrdinalIgnoreCase) >= 0);

C# Check if string contains any matches in a string array

You could combine the strings with regex or statements, and then "do it in one pass," but technically the regex would still performing a loop internally. Ultimately, looping is necessary.

Checking if a string array contains a value, and if so, getting its position

You could use the Array.IndexOf method:

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos > -1)
{
// the array contains the string and the pos variable
// will have its position in the array
}

C# - using string contains with string array

Similar question: Using C# to check if string contains a string in string array

This uses LINQ:

if(stringArray.Any(stringToCheck.Contains))

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(s => stringToCheck.Contains(s)))

How to return the String from String Array that contains a particular Substring in C#?

You can use LINQ:

var strXMLFileName = args.FirstOrDefault(x => x.Contains(".xml"));

Will yield null is there is no such argument.


NB: For the search string ".xml", EndsWith is usually more appropriate than Contains.

How to check if a string contains any of the elements in an string array?

Try this:

Search.Any(p => name.Contains(p))


Related Topics



Leave a reply



Submit