我想使用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'是否包含数组中的一个词?
当前回答
⚠️ 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 |
最简单最简单的方法:
bool bol = Array.Exists(stringarray, E => E == 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
if (Array.IndexOf(array, Value) >= 0)
{
//Your stuff goes here
}
方法如下:
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 = "text1";
string[] stringArray = { "text1", "testtest", "test1test2", "test2text1" };
foreach (string x in stringArray)
{
if (stringToCheck.Contains(x))
{
// Process...
}
}
也许你正在寻找一个更好的解决方案……参考Anton Gogolev使用LINQ的答案。
您也可以尝试这个解决方案。
string[] nonSupportedExt = { ".3gp", ".avi", ".opus", ".wma", ".wav", ".m4a", ".ac3", ".aac", ".aiff" };
bool valid = Array.Exists(nonSupportedExt,E => E == ".Aac".ToLower());
string [] lines = {"text1", "text2", "etc"};
bool bFound = lines.Any(x => x == "Your string to be searched");
如果搜索的字符串与数组'lines'中的任何元素匹配,则bFound设置为true。