QUESTION 42 · String Operations
Explain string comparison using strcmp and why == is unsuitable for contents.
5 marksAnswer in brief
strcmp compares two null-terminated strings lexicographically, examining their contents rather than comparing pointer values.
Working
- Compare corresponding bytes from the beginning.
- Continue while they are equal and not at the end.
- At the first difference, the unsigned character values determine the result’s sign.
- If both strings end together without a difference, return zero.
Example
strcmp("Code", "Code") returns zero. The sample therefore prints Equal. Comparing a string with a longer string that starts with the same prefix treats the shorter completed prefix as earlier, since its null terminator is compared at that position.
Why not ==?
For pointer expressions referring to strings, == compares pointer values. Two pointers can identify different arrays containing equal text. Conversely, sharing one pointer does not perform a character-by-character text comparison. Use strcmp when the question is whether the stored text is equal.
Character rules
strcmp is case-sensitive and is not a general dictionary-order comparison for every language or locale. The exact encoding influences byte values. Do not hard-code an expected difference such as -32; inspect only the sign. For these introductory examples, use ordinary byte strings with valid termination.
Complexity
The function stops at the first difference or a terminating position. It may finish in O(1) for a first-byte difference, and needs up to O(min(m, n) + 1) byte comparisons for lengths m and n. It needs no growing output array, giving O(1) auxiliary space in the usual analysis.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
#include <string.h>
int main(void)
{
char a[] = "Code", b[] = "Code";
int result = strcmp(a, b);
if (result == 0) { puts("Equal"); }
else if (result < 0) { puts("First is earlier"); }
else { puts("First is later"); }
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
Equal