Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining whether a sentence contains a specific word

Tags:

string

c#

parsing

I want to know how to refer to a word of a sentence in a label. For example, I have:

label1.text = "books pencil pen ruler";

I want to say: "if label1.text contains the word "pen" then do something":

if (label1.text CONTAINS THE WORD "pen")
{
    // do something
}

How do I do this?

like image 456
Sindu_ Avatar asked Jul 04 '12 04:07

Sindu_


2 Answers

Use Regex word boundaries:

if (Regex.IsMatch(label1.text, @"\bpen\b"))
    // do something

Much more robust than checking IndexOf or Splitting. E.g. a simple IndexOf("pen") would match "open". Trying to fix that by making it IndexOf(" pen ") wouldn't match "pen other words". Or if you Split(' '), it will not match in "This sentence ends in pen.". Regex's word boundaries match all of these as you'd expect. You could split on more word boundary characters, but it's much easier to let the writers of the Regex class do the work for you, than to try to understand word boundaries yourself.

like image 55
Tim S. Avatar answered Oct 16 '22 16:10

Tim S.


You could use string.Split() to separate that text into tokens, and Array.Contains to check if the word is in the list.

string sentence = "books pencil pen ruler";
string[] words = sentence.Split(' ');
bool hasFox = words.Contains("pen");

If you want to allow for more delimiters than just space (e.g. Tab), you can add additional separators when using Split. If you care about case sensitivity of the match, you can use the overload of Contains that takes an IEqualityComparer.

like image 37
Eric J. Avatar answered Oct 16 '22 16:10

Eric J.