1

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";
2

3 Answers 3

3

Note that if you really want to match the word (and not things like "anyone"), you can use regular expressions:

string source = "is there any way to figure this out";
string match = @"\bany\b";
bool match = Regex.IsMatch(source, match);

You can also do case-insensitive match.

Sign up to request clarification or add additional context in comments.

Comments

3
String stringSource = "is there any way to figure this out";
String valueToCheck = "any";

if (stringSource.Contains(valueToCheck)) {

}

Comments

2

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:

  • if matchWordOnly is set to true, the function will return true for "any way" and false for "anyway"
  • if 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.

1 Comment

Also you can use Regex.Escape to prevent regex patterns being passed to the method, if needed. Though I cannot think of any word that is also a regex pattern...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.