354

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?

1

30 Answers 30

951

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))
17
  • 131
    Note to self: linq is amazing, linq is amazing, linq is amazing! Gotta' start using linq. May 26, 2010 at 11:41
  • 2
    @Spooks Linq To Objects (which is used in the answer's string-check) can be used via LinqBridge on .NET 2.0 albahari.com/nutshell/linqbridge.aspx Aug 24, 2012 at 20:12
  • 1
    how would you do this with case invariance?
    – Offler
    Jun 11, 2013 at 7:24
  • 20
    @Offler That would be stringArray.Any(s => s.IndexOf(stringToCheck, StringComparison.CurrentCultureIgnoreCase) > -1) Jun 11, 2013 at 9:20
  • 3
    how to get which item in the array matched?
    – ibubi
    Oct 25, 2017 at 8:33
173

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.

10
  • 5
    Thanks, I modified your code to: if (stringToCheck.Contains(s)) and it worked.
    – Theomax
    May 26, 2010 at 13:29
  • 5
    I did if (stringArray.Contains(stringToCheck)) and it works great, thanks.
    – Tamara JQ
    Oct 19, 2011 at 14:18
  • 84
    Don't use this answer use LINQ instead
    – AlexC
    Mar 23, 2012 at 11:19
  • 13
    Little note to people who do not see Contains method on the string array: Check if you have a "using System.Linq;" namespace in your codefile :) Apr 5, 2012 at 10:33
  • 5
    Linq isn't always available in legacy software. Aug 7, 2013 at 17:17
49
⚠️ Note: this does not answer the question asked
The question asked is "how can I check if a sentence contains any word from a list of words?"
This answer checks if a list of words contains one particular word

Try this:

No need to use LINQ

if (Array.IndexOf(array, Value) >= 0)
{
    //Your stuff goes here
}
4
  • Nice! And what benefit could Linq possibly have over Array.IndexOf?? Nov 6, 2013 at 20:19
  • 28
    This doesn't solve the question at all. IndexOf tells you if an array contains an exact match for a string, the original question is if a string contains one of an array of strings, which Linq handles easily.
    – NetMage
    Jun 19, 2014 at 17:53
  • 1
    I know this comment is late, but just to those who don't know, a string is an array of characters so string types do contain an IndexOf method... so @NetMage it is a possible solution. Jun 13, 2016 at 14:45
  • 5
    @Blacky Wolf, Did you read the question? Array.IndexOf tells you if an array contains a value, the OP wanted to know if a value contains any member of an array, exactly the opposite of this answer. You could use String.IndexOf with Linq: stringArray.Any(w => stringToCheck.IndexOf(w) >= 0) but the Linq answer using String.Contains makes more sense, as that is exactly what is being asked for.
    – NetMage
    Oct 6, 2016 at 23:51
49
⚠️ Note: this does not answer the question asked
The question asked is "how can I check if a sentence contains any word from a list of words?"
This answer checks if a list of words contains one particular word

Just use linq method:

stringArray.Contains(stringToCheck)
5
  • 7
    Note, that Contains is a extension method and you need to do using System.Linq;
    – isHuman
    Mar 10, 2016 at 9:53
  • 14
    This answer is backwards from the question.
    – NetMage
    Oct 6, 2016 at 23:51
  • 2
    How has this answer been upvoted so many times? 5 years after the question is asked and the solution is basically reversed of what the question is asking.
    – Fus Ro Dah
    Mar 27, 2018 at 21:46
  • 1
    maybe just reverse the variable names it will be ok? May 13, 2019 at 19:40
  • @Jean-FrançoisFabre that will call string.Contains, which is different to array.Contains, and string.Contains does not have an overload that accepts an array of string
    – Caius Jard
    Mar 20 at 8:30
10
⚠️ Note: this does not answer the question asked
The question asked is "how can I check if a sentence contains any word from a list of words?"
This answer checks if a list of words contains one particular word

Easiest and sample way.

  bool bol=Array.Exists(stringarray,E => E == stringtocheck);
2
  • better is stringarray.Exists(entity => entity == stringtocheck) Dec 14, 2016 at 15:26
  • I think you cant call exists method directly from string array.Exists method can use directly for list<T>.So should use static method array.exist<T> for string array.check here => msdn.microsoft.com/en-us/library/yw84x8be(v=vs.110).aspx
    – lwin
    Dec 15, 2016 at 4:24
8
⚠️ Note: this does not answer the question asked
The question asked is "how can I check if a sentence contains any word from a list of words?"
This answer checks if a list of words contains one particular word
string strName = "vernie";
string[] strNamesArray = { "roger", "vernie", "joel" };

if (strNamesArray.Any(x => x == strName))
{
   // do some action here if true...
}
1
  • 2
    I don't think this is what the question is asking for.
    – Pang
    Apr 18, 2016 at 1:25
4

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!");
}
2
  • This is a better solution, since it's a substring check against words in a list instead of an exact match check.
    – Roy B
    Mar 10, 2015 at 19:04
  • Nice answer, but wow that is hard to read compared to modern C# even without Linq; also, String.Contains might be better than String.IndexOf unless you want to ignore case, since Microsoft forgot a two argument String.Contains you have to write your own. Consider: Array.Exists(stringArray, s => stringToCheck.IndexOf(s, StringComparison.OrdinalIgnoreCase) > -1)
    – NetMage
    Oct 7, 2016 at 0:00
4
⚠️ Note: this does not answer the question asked
The question asked is "how can I check if a sentence contains any word from a list of words?"
This answer checks if a list of words contains one particular word
  stringArray.ToList().Contains(stringToCheck)
3

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;
3

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();
        }
    }
2

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;
}
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) { 
    // ....
}
1

To complete the above answers, for IgnoreCase check use:

stringArray.Any(s => stringToCheck.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) > -1)
1
  • Is there any way to get the index of the match with that also? Thanks.
    – Si8
    Apr 11, 2019 at 19:46
1

Using Find or FindIndex methods of the Array class:

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

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

0
1

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());
1

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 isContain = stringArray.Contains(stringToCheck);
1

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

using System.Linq;
if(stringArray1.Any(stringArray2.Contains))

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

using System.Linq;
if(stringArray1.All(stringArray2.Contains))
3
  • The second array doesn't have a "Contains" object!
    – Mahmut EFE
    Mar 15 at 3:47
  • @Mahmut you need to be using System.Linq namespace.
    – Scotty.NET
    Mar 15 at 12:46
  • @Scott.Net .. Contains property exist on for string type. It's not exist for an Array type.
    – Mahmut EFE
    Mar 15 at 15:13
1
⚠️ Note: this does not answer the question asked
The question asked is "how can I check if a sentence contains any word from a list of words?"
This answer checks if a list of words contains one particular word

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

new[] {"text1", "text2", "etc"}.Contains(ItemToFind);
0
1
⚠️ Note: this does not answer the question asked
The question asked is "how can I check if a sentence contains any word from a list of words?"
This answer checks if a list of words contains one particular word

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

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

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));
0
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'.

0
-1

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));
-1
public bool ContainAnyOf(string word, string[] array) 
    {
        for (int i = 0; i < array.Length; i++)
        {
            if (word.Contains(array[i]))
            {
                return true;
            }
        }
        return false;
    }
-1

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.

-1

Simple solution, not required linq any

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

1
  • 2
    What if one of the values in the array contains your delimiter? Jul 21, 2016 at 19:04
-1
int result = Array.BinarySearch(list.ToArray(), typedString, StringComparer.OrdinalIgnoreCase);
-1

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

}
-2

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";
        }
    }
}
1
  • 4
    This sets Text = "matched" as many times as stringToCheck contains substrings of stringArray. You may want to put a break or return after the assignment. May 26, 2010 at 13:55
-3

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();
    }
}
1
  • 1
    Your second two options don't even do the same thing at the first one. Apr 4, 2018 at 18:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.