0

Let's take an example of English sentence:

string sentence = "Hello, How are you?";

So if I want to search a word "you", I would use:

if (sentence.Contains("you")); // This would be true

But if I search this:

if (sentence.Contains("ello")); // This would also be true

But I want it to be False. I want to search the whole word. Not a part of word

How to do so in C#?

juvchan
  • 6,113
  • 2
  • 22
  • 35
Zaif Senpai
  • 71
  • 3
  • 11

3 Answers3

6

You can do this using regex.

var search = "ello";

string sentence = "Hello, How are you?";

string pattern = string.Format(@"\b{0}\b", search);

if(Regex.IsMatch(sentence, pattern))
{
}
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
1

You can split the sentence with Regex.Split() by word boundary and search for the word with simple Enumerable.Contains. It may be useful when you have to search for multiple words in one sentence (Just put them later into some HashSet for even better lookup):

var line = "Hello, How are you ? ";
var pattern = @"\b";

var words = new HashSet<String>(Regex.Split(line, pattern));

Console.WriteLine(words.Contains("Hello"));
Console.WriteLine(words.Contains("ello"));
Console.WriteLine(words.Contains("How"));

Or if you want to search for a single word once in a while, you can search directly by regex escaping the word and combining it with @"\b":

var line = "Hello, How are you ? ";
var wordBad = "ello";
var wordGood = "Hello";                    

Console.WriteLine(Regex.Match(line, $"\\b{Regex.Escape(wordBad)}\\b").Success);
Console.WriteLine(Regex.Match(line, $"\\b{Regex.Escape(wordGood)}\\b").Success);
Eugene Podskal
  • 10,270
  • 5
  • 31
  • 53
1

You can use String.Split (combined with Select to remove punctuation) to get a list of words from the sentence, and then use Enumerable.Contains on that list:

var res = sentence.Split().Select(str => String.Join("", str.Where(c => Char.IsLetterOrDigit(c))))
                  .Contains("ello");

Console.WriteLine(res); //  False
w.b
  • 11,026
  • 5
  • 30
  • 49