I have two strings:
string1 = "theater is small"; string2 = "The small thing in the world";
I need to check weather the string "the" is present in the strings or not.
I can use the contains function, but can it do a whole word match? i.e it should not match with "theater" of string1!
You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.
The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
strcmp() in C/C++ This function is used to compare the string arguments. It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found.
The simplest solution is to use regular expressions and the word boundary delimiter \b
:
bool result = Regex.IsMatch(text, "\\bthe\\b");
or, if you want to find mismatching capitalisation,
bool result = Regex.IsMatch(text, "\\bthe\\b", RegexOptions.IgnoreCase);
(using System.Text.RegularExpressons
.)
Alternatively, you can split your text into individual words and search the resulting array. However, this isn’t always trivial because it’s not enough to split on white spaces; this would ignore all punctuation and yield wrong results. A solution is to once again use regular expressions, namely Regex.Split
.
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