-5

I'm looking for a way of detecting wheter or not a certain word is present in a string. For example, if I have the string "hi, this is me" I want to make sure "hi" is present; What I tried so far:

bool containsWord () {
    string str = "hi, this is me";
    return str.Contains ("hi");
}

Does not work properly: the problem with this is that I need to make sure the word itself is present and is not part of another word. With the code as it is, doing:

bool containsWord () {
    string str = "this is me";
    return str.Contains ("hi");
}

would still return true since "hi" is still a substring of "this". How can I avoid that?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Lextredis
  • 11
  • 2
  • 2
    [`Regex`](https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex%28v=vs.110%29.aspx). – Wai Ha Lee Dec 09 '15 at 14:30

2 Answers2

3

How about using String.Split

 // Add other punctuation if need 
var array = str.Split(" ,;.".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) ;
bool containsWord = array.Any(s => s.Equals("hi", StringComparison.InvariantCultureIgnoreCase)); 
Perfect28
  • 11,089
  • 3
  • 25
  • 45
2

use some regular expressions - Regex.IsMatch(@"\bhi\b");
don't forget to add using System.Text.RegularExpressions;

Konstantin Zadiran
  • 1,485
  • 2
  • 22
  • 35