我想使用c#检查字符串值是否包含字符串数组中的单词。例如,
string stringToCheck = "text1text2text3";
string[] stringArray = { "text1", "someothertext", etc... };
if(stringToCheck.contains stringArray) //one of the items?
{
}
我如何检查字符串值'stringToCheck'是否包含数组中的一个词?
我想使用c#检查字符串值是否包含字符串数组中的单词。例如,
string stringToCheck = "text1text2text3";
string[] stringArray = { "text1", "someothertext", etc... };
if(stringToCheck.contains stringArray) //one of the items?
{
}
我如何检查字符串值'stringToCheck'是否包含数组中的一个词?
当前回答
方法如下:
using System.Linq;
if(stringArray.Any(stringToCheck.Contains))
/* or a bit longer: (stringArray.Any(s => stringToCheck.Contains(s))) */
这个函数检查stringToCheck是否包含stringArray的子字符串。如果你想确保它包含所有的子字符串,将Any更改为all:
if(stringArray.All(stringToCheck.Contains))
其他回答
也许是这样的:
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!");
}
⚠️ 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
}
⚠️ 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...
}
方法如下:
using System.Linq;
if(stringArray.Any(stringToCheck.Contains))
/* or a bit longer: (stringArray.Any(s => stringToCheck.Contains(s))) */
这个函数检查stringToCheck是否包含stringArray的子字符串。如果你想确保它包含所有的子字符串,将Any更改为all:
if(stringArray.All(stringToCheck.Contains))
LINQ:
arrray。Any(x => word.Equals(x));
这是为了查看数组是否包含单词(精确匹配)。使用. contains作为子字符串,或者其他任何你可能需要应用的逻辑。