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";
AWinkle
  • 673
  • 8
  • 18
Jonathan A
  • 21
  • 1
  • You should use of Regex Expressions to match `any` word in a string – Behzad Aug 06 '15 at 19:20
  • 2
    possible duplicate of [How can I check if a string exists in another string](http://stackoverflow.com/questions/5848337/how-can-i-check-if-a-string-exists-in-another-string) – lhoworko Aug 06 '15 at 19:48

3 Answers3

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

if (stringSource.Contains(valueToCheck)) {

}
smoggers
  • 3,154
  • 6
  • 26
  • 38
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.

IS4
  • 11,945
  • 2
  • 47
  • 86
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.
Community
  • 1
  • 1
trashr0x
  • 6,457
  • 2
  • 29
  • 39
  • 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... – IS4 Nov 12 '16 at 23:33