Compare Strings with strcmp() in C++: Examples & Best Practices
This Snippet is coded by a user inOnline cpp Compiler. You can see and run this code too.
زبان: C++
std::strcmp() compares two null-terminated C-style strings character by character. Its signature is int strcmp(const char* lhs, const char* rhs);. It evaluates characters as unsigned char and stops at the first mismatch or when both strings reach their null terminator. The return value is negative if lhs is lexicographically less than rhs, zero if they are identical, and positive if lhs is greater. Because only the sign matters, compare the result with 0 rather than relying on a specific number.
Inputs/outputs: Provide two valid null-terminated strings, such as string literals or std::string::c_str() results. The function returns an int indicating relative order. Example: strcmp("apple", "banana") returns a negative value; strcmp("apple", "apple") returns 0. Comparison is case-sensitive, so "Apple" and "apple" differ.
Complexity: Time complexity is O(n), where n is the number of characters examined up to the first difference or the end of the shorter string. Space complexity is O(1). Include <cstring> before calling std::strcmp(). Both arguments must point to valid null-terminated byte strings; passing a null pointer or an unterminated array causes undefined behavior. The function does not allocate memory or modify either string. For std::string, prefer ==, <, or compare() for type safety; use strcmp() mainly for C APIs and legacy code.