我想使用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'是否包含数组中的一个词?
当前回答
string [] lines = {"text1", "text2", "etc"};
bool bFound = lines.Any(x => x == "Your string to be searched");
如果搜索的字符串与数组'lines'中的任何元素匹配,则bFound设置为true。
其他回答
我使用下面的代码来检查字符串是否包含字符串数组中的任何项:
foreach (string s in stringArray)
{
if (s != "")
{
if (stringToCheck.Contains(s))
{
Text = "matched";
}
}
}
在我的案例中,上述答案并不奏效。我正在检查数组中的字符串,并将其分配给布尔值。我修改了Anton Gogolev的答案,并删除了Any()方法,并将stringToCheck放在Contains()方法内。
bool isContain = stringArray.Contains(stringToCheck);
要完成前面的回答,对于IgnoreCase检查,使用:
stringArray.Any(s => stringToCheck.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) > -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 |
只需使用LINQ方法:
stringArray.Contains(stringToCheck)
使用LINQ和方法组将是最快和更紧凑的方法。
var arrayA = new[] {"element1", "element2"};
var arrayB = new[] {"element2", "element3"};
if (arrayB.Any(arrayA.Contains))
return true;