[c#] 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?

This question is related to c# arrays string search

The answer is


public bool ContainAnyOf(string word, string[] array) 
    {
        for (int i = 0; i < array.Length; i++)
        {
            if (word.Contains(array[i]))
            {
                return true;
            }
        }
        return false;
    }

try this, here the example : To check if the field contains any of the words in the array. To check if the field(someField) contains any of the words in the array.

String[] val = { "helloword1", "orange", "grape", "pear" };   

Expression<Func<Item, bool>> someFieldFilter = i => true;

someFieldFilter = i => val.Any(s => i.someField.Contains(s));

stringArray.ToList().Contains(stringToCheck)

You can also do the same thing as Anton Gogolev suggests to check if any item in stringArray1 matches any item in stringArray2:

if(stringArray1.Any(stringArray2.Contains))

And likewise all items in stringArray1 match all items in stringArray2:

if(stringArray1.All(stringArray2.Contains))

Try this

string stringToCheck = "text1text2text3";
string[] stringArray = new string[] { "text1" };

var t = lines.ToList().Find(c => c.Contains(stringToCheck));

It will return you the line with the first incidence of the text that you are looking for.


int result = Array.BinarySearch(list.ToArray(), typedString, StringComparer.OrdinalIgnoreCase);

To complete the above answers, for IgnoreCase check use:

stringArray.Any(s => stringToCheck.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) > -1)

Using Find or FindIndex methods of the Array class:

if(Array.Find(stringArray, stringToCheck.Contains) != null) 
{ 
}
if(Array.FindIndex(stringArray, stringToCheck.Contains) != -1) 
{ 
}

I used a similar method to the IndexOf by Maitrey684 and the foreach loop of Theomax to create this. (Note: the first 3 "string" lines are just an example of how you could create an array and get it into the proper format).

If you want to compare 2 arrays, they will be semi-colon delimited, but the last value won't have one after it. If you append a semi-colon to the string form of the array (i.e. a;b;c becomes a;b;c;), you can match using "x;" no matter what position it is in:

bool found = false;
string someString = "a-b-c";
string[] arrString = someString.Split('-');
string myStringArray = arrString.ToString() + ";";

foreach (string s in otherArray)
{
    if (myStringArray.IndexOf(s + ";") != -1) {
       found = true;
       break;
    }
}

if (found == true) { 
    // ....
}

Just use linq method:

stringArray.Contains(stringToCheck)

For my case, the above answers did not work. I was checking for a string in an array and assigning it to a boolean value. I modified @Anton Gogolev's answer and removed the Any() method and put the stringToCheck inside the Contains() method.

bool = stringArray.Contains(stringToCheck);

You can try this solution as well.

string[] nonSupportedExt = { ".3gp", ".avi", ".opus", ".wma", ".wav", ".m4a", ".ac3", ".aac", ".aiff" };
        
bool valid = Array.Exists(nonSupportedExt,E => E == ".Aac".ToLower());

I use the following in a console application to check for arguments

var sendmail = args.Any( o => o.ToLower() == "/sendmail=true");

Most of those solution is correct, but if You need check values without case sensitivity

using System.Linq;
...
string stringToCheck = "text1text2text3";
string[] stringArray = { "text1", "someothertext"};

if(stringArray.Any(a=> String.Equals(a, stringToCheck, StringComparison.InvariantCultureIgnoreCase)) )
{ 
   //contains
}

if (stringArray.Any(w=> w.IndexOf(stringToCheck, StringComparison.InvariantCultureIgnoreCase)>=0))
{
   //contains
}

dotNetFiddle example


I would use Linq but it still can be done through:

new[] {"text1", "text2", "etc"}.Contains(ItemToFind);

You can define your own string.ContainsAny() and string.ContainsAll() methods. As a bonus, I've even thrown in a string.Contains() method that allows for case-insensitive comparison, etc.

public static class Extensions
{
    public static bool Contains(this string source, string value, StringComparison comp)
    {
        return source.IndexOf(value, comp) > -1;
    }

    public static bool ContainsAny(this string source, IEnumerable<string> values, StringComparison comp = StringComparison.CurrentCulture)
    {
        return values.Any(value => source.Contains(value, comp));
    }

    public static bool ContainsAll(this string source, IEnumerable<string> values, StringComparison comp = StringComparison.CurrentCulture)
    {
        return values.All(value => source.Contains(value, comp));
    }
}

You can test these with the following code:

    public static void TestExtensions()
    {
        string[] searchTerms = { "FOO", "BAR" };
        string[] documents = {
            "Hello foo bar",
            "Hello foo",
            "Hello"
        };

        foreach (var document in documents)
        {
            Console.WriteLine("Testing: {0}", document);
            Console.WriteLine("ContainsAny: {0}", document.ContainsAny(searchTerms, StringComparison.OrdinalIgnoreCase));
            Console.WriteLine("ContainsAll: {0}", document.ContainsAll(searchTerms, StringComparison.OrdinalIgnoreCase));
            Console.WriteLine();
        }
    }

string [] lines = {"text1", "text2", "etc"};

bool bFound = lines.Any(x => x == "Your string to be searched");

bFound sets to true if searched string is matched with any element of array 'lines'.


Try this:

No need to use LINQ

if (Array.IndexOf(array, Value) >= 0)
{
    //Your stuff goes here
}

Using Linq and method group would be the quickest and more compact way of doing this.

var arrayA = new[] {"element1", "element2"};
var arrayB = new[] {"element2", "element3"};
if (arrayB.Any(arrayA.Contains)) return true;

string strName = "vernie";
string[] strNamesArray = { "roger", "vernie", "joel" };

if (strNamesArray.Any(x => x == strName))
{
   // do some action here if true...
}

I used the following code to check if the string contained any of the items in the string array:

foreach (string s in stringArray)
{
    if (s != "")
    {
        if (stringToCheck.Contains(s))
        {
            Text = "matched";
        }
    }
}

Three options demonstrated. I prefer to find the third as the most concise.

class Program {
    static void Main(string[] args) {
    string req = "PUT";
    if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
        Console.WriteLine("one.1.A");  // IS TRUE
    }
    req = "XPUT";
    if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
        Console.WriteLine("one.1.B"); // IS TRUE
    }
    req = "PUTX";
    if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
        Console.WriteLine("one.1.C");  // IS TRUE
    }
    req = "UT";
    if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
        Console.WriteLine("one.1.D"); // false
    }
    req = "PU";
    if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
        Console.WriteLine("one.1.E"); // false
    }
    req = "POST";
    if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
        Console.WriteLine("two.1.A"); // IS TRUE
    }
    req = "ASD";
    if ((new string[] {"PUT", "POST"}).Any(s => req.Contains(s))) {
        Console.WriteLine("three.1.A");  // false
    }


    Console.WriteLine("-----");
    req = "PUT";
    if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0)  {
        Console.WriteLine("one.2.A"); // IS TRUE
    }
    req = "XPUT";
    if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0)  {
        Console.WriteLine("one.2.B"); // false
    }
    req = "PUTX";
    if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0)  {
        Console.WriteLine("one.2.C"); // false
    }
    req = "UT";
    if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0)  {
        Console.WriteLine("one.2.D"); // false
    }
    req = "PU";
    if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0)  {
        Console.WriteLine("one.2.E"); // false
    }
    req = "POST";
    if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0)  {
        Console.WriteLine("two.2.A");  // IS TRUE
    }
    req = "ASD";
    if (Array.IndexOf((new string[] {"PUT", "POST"}), req) >= 0)  {
        Console.WriteLine("three.2.A");  // false
    }

    Console.WriteLine("-----");
    req = "PUT";
    if ((new string[] {"PUT", "POST"}.Contains(req)))  {
        Console.WriteLine("one.3.A"); // IS TRUE
    }
    req = "XPUT";
    if ((new string[] {"PUT", "POST"}.Contains(req)))  {
        Console.WriteLine("one.3.B");  // false
    }
    req = "PUTX";
    if ((new string[] {"PUT", "POST"}.Contains(req)))  {
        Console.WriteLine("one.3.C");  // false
    }
    req = "UT";
    if ((new string[] {"PUT", "POST"}.Contains(req)))  {
        Console.WriteLine("one.3.D");  // false
    }
    req = "PU";
    if ((new string[] {"PUT", "POST"}.Contains(req)))  {
        Console.WriteLine("one.3.E");  // false
    }
    req = "POST";
    if ((new string[] {"PUT", "POST"}.Contains(req)))  {
        Console.WriteLine("two.3.A");  // IS TRUE
    }
    req = "ASD";
    if ((new string[] {"PUT", "POST"}.Contains(req)))  {
        Console.WriteLine("three.3.A");  // false
    }

    Console.ReadKey();
    }
}

Something like this perhaps:

string stringToCheck = "text1text2text3";
string[] stringArray = new string[] { "text1" };
if (Array.Exists<string>(stringArray, (Predicate<string>)delegate(string s) { 
    return stringToCheck.IndexOf(s, StringComparison.OrdinalIgnoreCase) > -1; })) {
    Console.WriteLine("Found!");
}

Here's how:

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))

Try:

String[] val = { "helloword1", "orange", "grape", "pear" };
String sep = "";
string stringToCheck = "word1";

bool match = String.Join(sep,val).Contains(stringToCheck);
bool anothermatch = val.Any(s => s.Contains(stringToCheck));

Simple solution, not required linq any

String.Join(",", array).Contains(Value+",");


Try this, no need for a loop..

string stringToCheck = "text1";
List<string> stringList = new List<string>() { "text1", "someothertext", "etc.." };
if (stringList.Exists(o => stringToCheck.Contains(o)))
{

}

Easiest and sample way.

  bool bol=Array.Exists(stringarray,E => E == stringtocheck);

If stringArray contains a large number of varied length strings, consider using a Trie to store and search the string array.

public static class Extensions
{
    public static bool ContainsAny(this string stringToCheck, IEnumerable<string> stringArray)
    {
        Trie trie = new Trie(stringArray);
        for (int i = 0; i < stringToCheck.Length; ++i)
        {
            if (trie.MatchesPrefix(stringToCheck.Substring(i)))
            {
                return true;
            }
        }

        return false;
    }
}

Here is the implementation of the Trie class

public class Trie
{
    public Trie(IEnumerable<string> words)
    {
        Root = new Node { Letter = '\0' };
        foreach (string word in words)
        {
            this.Insert(word);
        }
    }

    public bool MatchesPrefix(string sentence)
    {
        if (sentence == null)
        {
            return false;
        }

        Node current = Root;
        foreach (char letter in sentence)
        {
            if (current.Links.ContainsKey(letter))
            {
                current = current.Links[letter];
                if (current.IsWord)
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }

        return false;
    }

    private void Insert(string word)
    {
        if (word == null)
        {
            throw new ArgumentNullException();
        }

        Node current = Root;
        foreach (char letter in word)
        {
            if (current.Links.ContainsKey(letter))
            {
                current = current.Links[letter];
            }
            else
            {
                Node newNode = new Node { Letter = letter };
                current.Links.Add(letter, newNode);
                current = newNode;
            }
        }

        current.IsWord = true;
    }

    private class Node
    {
        public char Letter;
        public SortedList<char, Node> Links = new SortedList<char, Node>();
        public bool IsWord;
    }

    private Node Root;
}

If all strings in stringArray have the same length, you will be better off just using a HashSet instead of a Trie

public static bool ContainsAny(this string stringToCheck, IEnumerable<string> stringArray)
{
    int stringLength = stringArray.First().Length;
    HashSet<string> stringSet = new HashSet<string>(stringArray);
    for (int i = 0; i < stringToCheck.Length - stringLength; ++i)
    {
        if (stringSet.Contains(stringToCheck.Substring(i, stringLength)))
        {
            return true;
        }
    }

    return false;
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript Find a file by name in Visual Studio Code Search all the occurrences of a string in the entire project in Android Studio Java List.contains(Object with field value equal to x) Trigger an action after selection select2 How can I search for a commit message on GitHub? SQL search multiple values in same field Find a string by searching all tables in SQL Server Management Studio 2008 Search File And Find Exact Match And Print Line? Java - Search for files in a directory How to put a delay on AngularJS instant search?