Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String compare C# - whole word match

Tags:

c#

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!

like image 654
siva Avatar asked Oct 11 '10 08:10

siva


People also ask

Can you use == to compare strings in C?

You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.

Can I compare strings in C?

The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.

Can you use == to compare two strings?

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.

What is strcmp function in C?

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.


1 Answers

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.

like image 129
Konrad Rudolph Avatar answered Sep 20 '22 14:09

Konrad Rudolph