我需要使用C#代码编写一个if语句,它将检测单词" any"存在于字符串中:
string source ="is there any way to figure this out";
答案 0 :(得分:3)
String stringSource = "is there any way to figure this out";
String valueToCheck = "any";
if (stringSource.Contains(valueToCheck)) {
}
答案 1 :(得分:3)
请注意,如果您真的想要匹配单词(而不是“任何人”之类的东西),您可以使用正则表达式:
string source = "is there any way to figure this out";
string match = @"\bany\b";
bool match = Regex.IsMatch(source, match);
您也可以进行不区分大小写的匹配。
答案 2 :(得分:2)
这是一种结合和扩展IllidanS4和smoggers的答案的方法:
10
您现在可以执行以下操作:
public bool IsMatch(string inputSource, string valueToFind, bool matchWordOnly)
{
var regexMatch = matchWordOnly ? string.Format(@"\b{0}\b", valueToFind) : valueToFind;
return System.Text.RegularExpressions.Regex.IsMatch(inputSource, regexMatch);
}
注意:
var source = "is there any way to figure this out";
var value = "any";
var isWordDetected = IsMatch(source, value, true); //returns true, correct
设置为matchWordOnly
,则该函数将返回true
的{{1}}和true
的{{1}} "any way"
设置为false
,则该函数将为"anyway"
和matchWordOnly
返回false
。这是合乎逻辑的,因为"任何"在true
中成为一个单词,它首先需要成为字符串的一部分。 "any way"
(正则表达式中\b
的否定)可以添加到混合中以仅匹配非单词,但我发现根据您的要求不需要。