我想使用c#检查字符串值是否包含字符串数组中的单词。例如,

string stringToCheck = "text1text2text3";

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

if(stringToCheck.contains stringArray) //one of the items?
{

}

我如何检查字符串值'stringToCheck'是否包含数组中的一个词?


当前回答

我使用了类似于Maitrey684的IndexOf方法和Theomax的foreach循环来创建它。(注意:前3个“字符串”行只是一个例子,你可以创建一个数组,并把它变成适当的格式)。

如果您想比较两个数组,它们将以分号分隔,但最后一个值后面不会有分号。如果你在数组的字符串形式中添加了一个分号(即a;b;c变成了a;b;c;),你可以使用"x;"进行匹配,无论它在什么位置:

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

其他回答

要完成前面的回答,对于IgnoreCase检查,使用:

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

试试这个。示例:检查字段是否包含数组中的任何单词。检查字段(someField)是否包含数组中的任何单词。

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

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

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

试试这个。没有任何循环的需要。

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

}
⚠️ 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

试试这个:

不需要使用LINQ

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

你可以定义自己的string.ContainsAny()和string.ContainsAll()方法。作为奖励,我甚至还抛出了一个string.Contains()方法,该方法允许不区分大小写的比较等等。

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

你可以用下面的代码进行测试:

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