strcmp() Compare two complete strings
strcmp() Compare two complete strings
strcmp() compares unsigned char values and returns negative, zero, or positive. Only the sign matters; it is case-sensitive and ignores locale collation.
| Category | string.h strings |
|---|---|
| Kind | Library function |
| Header | <string.h> |
| C standard | C89 / C90 |
📝 Syntax
int strcmp(const char *str1, const char *str2);
⚙️ Parameters
| str1 Required | The first null-terminated string. |
|---|---|
| str2 Required | The second null-terminated string. |
Returns: Returns a negative value, zero, or a positive value when str1 is less than, equal to, or greater than str2, respectively.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
Equal result: 0
apple before apply: yes
⚠️ Warning Rely only on the sign of the result; implementations need not return exactly -1, 0, or 1.
💡 Tip Comparison is case-sensitive and uses byte values rather than locale-specific natural collation rules.
🏷️ Related string.h functions
📚 Related Tutorials
❓ FAQ
QDoes strcmp always return -1, 0, or 1?
ANo. Equality produces zero, but unequal strings are guaranteed only a positive or negative result, not a particular magnitude.
QIs strcmp case-sensitive?
AYes. For example, "Apple" and "apple" differ. Case-insensitive comparison requires an explicit choice of character and language rules.
QCan strcmp compare strings using natural collation rules for Chinese or other languages?
ANo. strcmp compares unsigned char byte values one by one, with no understanding of linguistic ordering, accent combinations, or localization rules, and it is case-sensitive. Consider strcoll() when you need the current locale's collation rules. For full Unicode text, also define the encoding and use a library that supports the appropriate collation.