What is strcmp()?
The strcmp() function compares two strings lexicographically (dictionary order) character by character. It returns an integer indicating whether the strings are equal or which one is greater.
Header File
#include <string.h>
Syntax
int strcmp(const char *str1, const char *str2);
Return Values
| Return Value | Meaning |
|---|---|
| 0 | Strings are equal |
| > 0 (positive) | str1 is greater than str2 |
| < 0 (negative) | str1 is less than str2 |
How Comparison Works
Compares ASCII values character by character until:
- A difference is found
- Null terminator (
\0) is reached
Basic Examples
Example 1: Equal Strings
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Hello";
int result = strcmp(str1, str2);
if(result == 0) {
printf("Strings are EQUAL\n");
}
printf("Return value: %d\n", result); // 0
return 0;
}
Example 2: Different Strings
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Apple";
char str2[] = "Banana";
int result = strcmp(str1, str2);
printf("'Apple' vs 'Banana': %d\n", result); // Negative (A < B)
printf("'Banana' vs 'Apple': %d\n", strcmp(str2, str1)); // Positive
if(result < 0) {
printf("'Apple' comes before 'Banana'\n");
}
return 0;
}
Example 3: Case Sensitivity
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "HELLO";
int result = strcmp(str1, str2);
printf("'hello' vs 'HELLO': %d\n", result);
// 'h' (104) vs 'H' (72) → 104 - 72 = 32 (positive)
if(result != 0) {
printf("strcmp() is CASE-SENSITIVE!\n");
}
return 0;
}
Practical Examples
Example 4: User Input Validation
#include <stdio.h>
#include <string.h>
int main() {
char username[50];
char password[50];
// Correct credentials
char correct_user[] = "admin";
char correct_pass[] = "secret123";
printf("Username: ");
scanf("%s", username);
printf("Password: ");
scanf("%s", password);
// Compare strings
if(strcmp(username, correct_user) == 0 &&
strcmp(password, correct_pass) == 0) {
printf("Login Successful!\n");
} else {
printf("Invalid username or password!\n");
}
return 0;
}
Example 5: Sorting Strings
#include <stdio.h>
#include <string.h>
int main() {
char fruits[5][20] = {"Banana", "Apple", "Mango", "Cherry", "Date"};
char temp[20];
// Bubble sort using strcmp
for(int i = 0; i < 4; i++) {
for(int j = i + 1; j < 5; j++) {
if(strcmp(fruits[i], fruits[j]) > 0) {
// Swap if fruits[i] > fruits[j]
strcpy(temp, fruits[i]);
strcpy(fruits[i], fruits[j]);
strcpy(fruits[j], temp);
}
}
}
printf("Sorted fruits:\n");
for(int i = 0; i < 5; i++) {
printf("%s\n", fruits[i]);
}
return 0;
}
/* Output:
Apple
Banana
Cherry
Date
Mango
*/
Example 6: Menu System
#include <stdio.h>
#include <string.h>
int main() {
char choice[10];
while(1) {
printf("\nMenu:\n");
printf("1. Start\n");
printf("2. Stop\n");
printf("3. Exit\n");
printf("Enter choice: ");
scanf("%s", choice);
if(strcmp(choice, "1") == 0 || strcmp(choice, "start") == 0) {
printf("Starting...\n");
}
else if(strcmp(choice, "2") == 0 || strcmp(choice, "stop") == 0) {
printf("Stopping...\n");
}
else if(strcmp(choice, "3") == 0 || strcmp(choice, "exit") == 0) {
printf("Exiting...\n");
break;
}
else {
printf("Invalid choice!\n");
}
}
return 0;
}
Example 7: Command Line Arguments
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
if(argc != 3) {
printf("Usage: %s <name> <age>\n", argv[0]);
return 1;
}
// Compare first argument
if(strcmp(argv[1], "admin") == 0) {
printf("Welcome Admin!\n");
} else {
printf("Hello %s\n", argv[1]);
}
// Check if age is numeric (simple check)
for(int i = 0; argv[2][i] != '\0'; i++) {
if(argv[2][i] < '0' || argv[2][i] > '9') {
printf("Age must be a number!\n");
return 1;
}
}
printf("Age: %s\n", argv[2]);
return 0;
}
Example 8: Searching in Array
#include <stdio.h>
#include <string.h>
int main() {
char names[6][20] = {"Alice", "Bob", "Charlie", "David", "Emma", "Frank"};
char search[20];
int found = -1;
printf("Enter name to search: ");
scanf("%s", search);
for(int i = 0; i < 6; i++) {
if(strcmp(names[i], search) == 0) {
found = i;
break;
}
}
if(found != -1) {
printf("'%s' found at index %d\n", search, found);
} else {
printf("'%s' not found\n", search);
}
return 0;
}
Detailed ASCII Comparison Examples
#include <stdio.h>
#include <string.h>
int main() {
// ASCII values for reference
printf("ASCII 'A': %d\n", 'A'); // 65
printf("ASCII 'a': %d\n", 'a'); // 97
printf("ASCII '0': %d\n", '0'); // 48
printf("\nComparison results:\n");
// Same string
printf("'cat' vs 'cat': %d\n", strcmp("cat", "cat")); // 0
// Different at first character
printf("'cat' vs 'dog': %d\n", strcmp("cat", "dog")); // 'c'(99)-'d'(100) = -1
// Different at later position
printf("'cat' vs 'car': %d\n", strcmp("cat", "car")); // 't'(116)-'r'(114) = 2
// One string is prefix of another
printf("'cat' vs 'catalog': %d\n", strcmp("cat", "catalog")); // '\0'(0)-'a'(97) = -97
printf("'catalog' vs 'cat': %d\n", strcmp("catalog", "cat")); // 'a'(97)-'\0'(0) = 97
// Uppercase vs lowercase
printf("'Apple' vs 'apple': %d\n", strcmp("Apple", "apple")); // 'A'(65)-'a'(97) = -32
return 0;
}
strcmp() vs Other Comparison Functions
| Function | Purpose | Case-Sensitive | Length Limited |
|---|---|---|---|
strcmp() | Full string compare | Yes | No |
strncmp() | Compare n characters | Yes | Yes |
strcasecmp() | Case-insensitive (non-standard) | No | No |
memcmp() | Compare memory blocks | N/A | Yes |
Example: strcmp vs strncmp
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Computer";
char str2[] = "Computing";
// strcmp compares entire string
printf("strcmp: %d\n", strcmp(str1, str2)); // 'e'(101)-'i'(105) = -4
// strncmp compares only first 4 chars
printf("strncmp (4 chars): %d\n", strncmp(str1, str2, 4)); // 0 (Comp == Comp)
// Check prefix
if(strncmp(str1, str2, 4) == 0) {
printf("Both start with 'Comp'\n");
}
return 0;
}
Example: Manual Implementation of strcmp
#include <stdio.h>
int my_strcmp(const char *s1, const char *s2) {
while(*s1 && *s2 && *s1 == *s2) {
s1++;
s2++;
}
return *s1 - *s2;
}
int main() {
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "World";
printf("Custom strcmp('Hello','Hello'): %d\n", my_strcmp(str1, str2)); // 0
printf("Custom strcmp('Hello','World'): %d\n", my_strcmp(str1, str3)); // Negative
return 0;
}
Common Patterns and Best Practices
Pattern 1: Check Equality
if(strcmp(str1, str2) == 0) {
// Strings are equal
}
Pattern 2: Check Not Equal
if(strcmp(str1, str2) != 0) {
// Strings are different
}
Pattern 3: Alphabetical Order
if(strcmp(str1, str2) < 0) {
// str1 comes before str2 alphabetically
}
Pattern 4: Safe Comparison with Length Check
#include <stdio.h>
#include <string.h>
int safe_strcmp(const char *s1, const char *s2, size_t max_len) {
return strncmp(s1, s2, max_len);
}
int main() {
char input[20];
printf("Enter 'quit' to exit: ");
fgets(input, sizeof(input), stdin);
// Remove newline
input[strcspn(input, "\n")] = '\0';
// Safe comparison
if(strcmp(input, "quit") == 0) {
printf("Exiting...\n");
}
return 0;
}
Common Mistakes
| Mistake | Wrong Code | Correct Code |
|---|---|---|
| Using = instead of == | if(strcmp(a,b) = 0) | if(strcmp(a,b) == 0) |
| Forgetting string.h | No include | #include <string.h> |
| Expecting 1 for equal | if(strcmp(a,b)) | if(strcmp(a,b) == 0) |
| Comparing incompatible types | strcmp("hi", 'h') | Both must be strings |
Quick Reference
| Condition | Code |
|---|---|
| Strings equal | strcmp(s1, s2) == 0 |
| Strings not equal | strcmp(s1, s2) != 0 |
| s1 < s2 (alphabetically) | strcmp(s1, s2) < 0 |
| s1 > s2 (alphabetically) | strcmp(s1, s2) > 0 |
| s1 comes before s2 | strcmp(s1, s2) < 0 |
Key Points
- Returns 0 when strings are identical
- Case-sensitive - 'A' and 'a' are different
- Compares ASCII values character by character
- Stops at null terminator or first difference
- Does NOT check buffer sizes - ensure strings are null-terminated
- Use
strncmp()for comparing only first n characters - Use
strcasecmp()for case-insensitive comparison (if available)
Complete Guide to Core & Advanced C Programming Concepts (Functions, Strings, Arrays, Loops, I/O, Control Flow)
https://macronepal.com/bash/building-blocks-of-c-a-complete-guide-to-functions/
Explains how functions in C work as reusable blocks of code, including declaration, definition, parameters, return values, and modular programming structure.
https://macronepal.com/bash/the-heart-of-text-processing-a-complete-guide-to-strings-in-c-2/
Explains how strings are handled in C using character arrays, string manipulation techniques, and common library functions for text processing.
https://macronepal.com/bash/the-cornerstone-of-data-organization-a-complete-guide-to-arrays-in-c/
Explains arrays in C as structured memory storage for multiple values, including indexing, initialization, and efficient data organization.
https://macronepal.com/bash/guaranteed-execution-a-complete-guide-to-the-do-while-loop-in-c/
Explains the do-while loop in C, where the loop body executes at least once before checking the condition.
https://macronepal.com/bash/mastering-iteration-a-complete-guide-to-the-for-loop-in-c/
Explains the for loop in C, including initialization, condition checking, and increment/decrement for controlled iteration.
https://macronepal.com/bash/mastering-iteration-a-complete-guide-to-while-loops-in-c/
Explains the while loop in C, focusing on condition-based repetition and proper loop control mechanisms.
https://macronepal.com/bash/beyond-if-else-a-complete-guide-to-switch-case-in-c/
Explains switch-case statements in C, enabling multi-branch decision-making based on variable values.
https://macronepal.com/bash/mastering-conditional-logic-a-complete-guide-to-if-else-statements-in-c/
Explains if-else statements in C for decision-making and controlling program flow based on conditions.
https://macronepal.com/bash/mastering-the-fundamentals-a-complete-guide-to-arithmetic-operations-in-c/
Explains arithmetic operations in C such as addition, subtraction, multiplication, division, and operator precedence.
https://macronepal.com/bash/foundation-of-c-programming-a-complete-guide-to-basic-input-output/
Explains basic input and output in C using scanf and printf for interacting with users and displaying results.
Online C Code Compiler
https://macronepal.com/free-online-c-code-compiler-2/