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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With