So I have a dilemma. I need to compare two C-style strings and I searched for the functions that would be the most appropiate:
memcmp //Compare two blocks of memory (function)
strcmp //Compare two strings (function )
strcoll //Compare two strings using locale (function)
strncmp //Compare characters of two strings (function)
strxfrm //Transform string using locale (function)
The first one I think is for addresses, so the idea is out. The second one sounds like the best choice to me, but I wanna hear feedback anyway. The other three leave me clueless.
The strcmp() function, is used to compare the strings (str1,str2). The strings str1 and str2 will be compared using this function. If the function returns a value 0, it signifies that the strings are equal otherwise, strings are not equal.
You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.
We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.
In the C Programming Language, the strcmp function returns a negative, zero, or positive integer depending on whether the object pointed to by s1 is less than, equal to, or greater than the object pointed to by s2.
For general string comparisons, strcmp
is the appropriate function. You should use strncmp
to only compare some number of characters from a string (for example, a prefix), and memcmp
to compare blocks of memory.
That said, since you're using C++, you should avoid this altogether and use the std::string
class, which is much easier to use and generally safer than C-style strings. You can compare two std::string
s for equality easily by just using the ==
operator.
Hope this helps!
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