I need to write an if statement using C# code which will detect if the word "any" exists in the string:
string source ="is there any way to figure this out";
Here is an approach combining and extending the answers of IllidanS4 and smoggers:
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);
}
You can now do stuff like:
var source = "is there any way to figure this out";
var value = "any";
var isWordDetected = IsMatch(source, value, true); //returns true, correct
Notes:
matchWordOnly is set to true, the function will return true for "any way" and false for "anyway" matchWordOnly is set to false, the function will return true for both "any way" and "anyway". This is logical as in order for "any" in "any way" to be a word, it needs to be a part of the string in the first place. \B (the negation of \b in the regular expression) can be added to the mix to match non-words only but I do not find it necessary based on your requirements.
anyword in a string