我想使用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;
...
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例子
其他回答
⚠️ 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 |
我在控制台应用程序中使用以下命令检查参数
var sendmail = args.Any( o => o.ToLower() == "/sendmail=true");
⚠️ 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)
⚠️ 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,但它仍然可以通过:
new[] {"text1", "text2", "etc"}.Contains(ItemToFind);
要完成前面的回答,对于IgnoreCase检查,使用:
stringArray.Any(s => stringToCheck.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) > -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;
}