Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper function for comparing two C-style strings?

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.

like image 922
Ren Avatar asked Feb 03 '12 00:02

Ren


People also ask

How do you compare strings in C?

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.

Can I 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.

Which function is used to compare the two given strings?

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.

Is there a compare function in C?

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.


1 Answers

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::strings for equality easily by just using the == operator.

Hope this helps!

like image 115
templatetypedef Avatar answered Sep 28 '22 10:09

templatetypedef