Jonathan A
Jonathan A

Reputation: 21

How to detect a particular word in a string using C#?

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

Upvotes: 1

Views: 1109

Answers (3)

trashr0x
trashr0x

Reputation: 6565

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.

Upvotes: 2

smoggers
smoggers

Reputation: 3192

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

if (stringSource.Contains(valueToCheck)) {

}

Upvotes: 3

IS4
IS4

Reputation: 13177

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.

Upvotes: 3

Related Questions