For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
strcmp in C programming is a function used to compare two strings. It checks the strings character by character to determine if they are equal or which one is lexicographically greater. In many C applications, comparing strings is crucial for tasks like sorting, searching, or validating input.
However, string comparison in C can be tricky, especially when dealing with case sensitivity or comparing dynamic strings.
In this guide, you’ll learn how to compare strings in C programming efficiently, through its syntax, usage, and practical examples.
Boost your C programming skills with our Software Development courses — take the next step in your learning journey!
strcmp in C programming is a standard library function that compares two strings. It is done character by character, and the function determines whether the strings are equal or which one is lexicographically greater or smaller.
A real-world example of using strcmp() for string validation would be comparing a user's password input against a stored password.
For instance, when a user logs into a system, strcmp() can be used to compare the entered password with the one stored in the system’s database.
The general syntax of the strcmp() function is as follows:
int strcmp(const char *str1, const char *str2);
Let’s break it down:
The strcmp() function is declared in the <string.h> header file, which is part of the C Standard Library. This header contains the necessary function declarations for string manipulation functions, including strcmp().
If you forget to include <string.h>, the compiler won’t recognize strcmp(), leading to a compilation error.
The program will likely generate an error message like "undefined reference to 'strcmp'," which means the compiler doesn't know what strcmp() is.
By including <string.h>, you gain access to a variety of functions for handling and manipulating strings, including strcmp(), which is specifically used to compare two null-terminated strings in C programming.
Let’s break down what the return value means:
Also Read: String Functions in C
Next, let's look at how to use strcmp in C programming for practical tasks like string comparison and sorting.
Here's how you can use it to compare two user-input strings for equality.
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100]; // Arrays to store user input strings
// Getting user input
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin); // Input first string
printf("Enter second string: ");
fgets(str2, sizeof(str2), stdin); // Input second string
// Remove newline characters that fgets() might add
str1[strcspn(str1, "\n")] = '\0';
str2[strcspn(str2, "\n")] = '\0';
// Comparing the strings using strcmp()
if (strcmp(str1, str2) == 0) { // Check if the strings are equal
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
return 0;
}
Output:
Enter first string: helloEnter second string: helloThe strings are equal.
Enter first string: helloEnter second string: worldThe strings are not equal.
Explanation:
Let’s dive into how strcmp() works under the hood.
Here's the step-by-step breakdown of how it works:
Stopping Condition:
Using strcmp() in C programming provides a reliable and precise way to compare strings, ensuring content is compared character by character, unlike relational operators such as ==, <, or >, which compare memory addresses or only the first character.
Let’s look at the details:
Key Takeaways:
Also Read: How to Implement Selection Sort in C?
Now that you know how strcmp() works, let's explore some examples.
These examples will help you understand how to handle case sensitivity, and even use strcmp() for sorting strings lexicographically.
Let’s dive into it!
The strcmp() function is case-sensitive, distinguishing between uppercase and lowercase characters.
In this example, let's compare "apple" and "Apple" to see how strcmp() behaves when case differences exist.
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "Apple";
// Comparing the strings using strcmp()
int result = strcmp(str1, str2); // Case-sensitive comparison
if (result == 0) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal. Result: %d\n", result); // Non-zero result
}
return 0;
}
Output:
The strings are not equal. Result: 32
Explanation:
Now, let's use strcmp() to sort an array of strings lexicographically (alphabetically). You’ll look at how it can be integrated into a sorting algorithm like Bubble Sort to sort an array of strings in ascending order.
#include <stdio.h>
#include <string.h>
void bubbleSort(char arr[][100], int n) {
char temp[100];
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (strcmp(arr[j], arr[j + 1]) > 0) { // Compare two strings
// Swap strings if they are out of order
strcpy(temp, arr[j]);
strcpy(arr[j], arr[j + 1]);
strcpy(arr[j + 1], temp);
}
}
}
}
int main() {
char fruits[][100] = {"Banana", "Apple", "Cherry", "Mango", "Pineapple"};
int n = sizeof(fruits) / sizeof(fruits[0]); // Number of strings in the array
printf("Before sorting:\n");
for (int i = 0; i < n; i++) {
printf("%s\n", fruits[i]);
}
// Sorting the array of strings
bubbleSort(fruits, n);
printf("\nAfter sorting:\n");
for (int i = 0; i < n; i++) {
printf("%s\n", fruits[i]);
}
return 0;
}
Output:
Before sorting:BananaAppleCherryMangoPineapple
After sorting:AppleBananaCherryMangoPineappleeapple
Explanation:
Key Takeaways:
Let’s move on to some common errors you should be aware of.
When using strcmp in C programming, there are a few common errors and misunderstandings that can cause issues, especially for beginners.
Let’s walk through some of them:
In C programming, strings must be null-terminated, meaning that the last character of the string must be the special character '\0' (null character).
If a string is not null-terminated, strcmp() will continue comparing characters beyond the end of the string, leading to undefined behavior or memory access errors.
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "hello "; // This string is not properly null-terminated
if (strcmp(str1, str2) == 0) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
return 0;
}
Output:
The strings are not equal.
Explanation:
A common mistake is confusing strcmp() with a pointer comparison using ==. In C, the == operator compares the addresses of the two strings (the memory locations where they are stored), not their content.
This can lead to unexpected results when comparing strings.
#include <stdio.h>
int main() {
char str1[] = "hello";
char str2[] = "hello"; // Both strings have the same content, but different addresses
if (str1 == str2) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
return 0;
}
Output:
The strings are not equal.
Explanation:
Avoiding these common pitfalls, you can effectively use strcmp in your C programming projects.
This quiz will test your understanding of the strcmp function in C and its various applications. Ready to challenge yourself? Let’s dive in and see how well you know this essential string-handling function in C programming!
1. What does the strcmp function return when two strings are identical?
A) 0
B) 1
C) -1
D) Undefined
2. Which of the following data types can be passed to the strcmp function?
A) char *
B) int *
C) float *
D) void *
3. What is the result of strcmp("apple", "apple")?
A) 0
B) A negative integer
C) A positive integer
D) Undefined
4. What will the strcmp function return if the first string is lexicographically smaller than the second string?
A) 1
B) 0
C) -1
D) Undefined
5. What happens when strcmp("apple", "Apple") is executed?
A) It returns 0
B) It returns a positive integer
C) It returns a negative integer
D) It throws a runtime error
6. When strcmp compares two strings, which of the following occurs first?
A) The function compares the first character of each string.
B) The function compares the last character of each string.
C) The function ignores case sensitivity.
D) The function compares the string lengths first.
7. How does strcmp treat case sensitivity?
A) It ignores case and compares strings lexicographically
B) It is case-sensitive and returns non-zero values for different cases
C) It converts all characters to uppercase
D) It compares based on ASCII values only
8. How can strcmp be used to sort an array of strings in C?
A) By using strcmp with qsort to compare strings
B) By passing the array to the sort function
C) By using strcmp in a for loop
D) By manually comparing each string
9. What is the primary limitation of using strcmp for comparing strings with different lengths?
A) It only works for strings of equal length
B) It doesn’t handle strings with null terminators properly
C) It stops comparing when a null character is found, so it may not properly compare strings of different lengths
D) It doesn’t support international characters
10. How can you avoid common errors when using strcmp in C, especially with null-terminated strings?
A) Always use strcmp for string comparisons
B) Ensure strings are properly null-terminated before comparison
C) Use strcmp with constant string literals only
D) Avoid using strcmp altogether
Understanding strcmp in C is just the beginning—keep building your C programming skills with expert-led courses and hands-on learning.
upGrad offers comprehensive courses to deepen your understanding of C programming, covering key topics such as string manipulation, algorithms, and memory management. By mastering functions like strcmp, you'll be equipped with the knowledge to tackle more advanced programming challenges, like building efficient data structures and optimizing code.
Explore upGrad’s specialized courses to level up your C programming skills:
You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!
Similar Reads:
Explore C Tutorials: From Beginner Concepts to Advanced Techniques
Array in C: Introduction, Declaration, Initialisation and More
Exploring Array of Pointers in C: A Beginner's Guide
What is C Function Call Stack: A Complete Tutorial
Binary Search in C
Constant Pointer in C: The Fundamentals and Best Practices
Dangling Pointer in C: Causes, Risks, and Prevention Techniques
Find Out About Data Structures in C and How to Use Them?
A. The strcmp in C programming function compares string content character by character, while == compares memory addresses, leading to incorrect results for string comparison.
A. strcmp in C programming is case-sensitive. It considers "apple" and "Apple" different due to ASCII value differences between lowercase and uppercase characters.
A. Yes, you can use strcmp in C with example in sorting algorithms, such as Bubble Sort or Quick Sort, to compare and arrange strings in lexicographical order.
A. strcmp() compares each character. If the strings differ in length, it stops comparing when the null character (\0) is encountered in the shorter string, returning the difference in ASCII values.
A. strcmp() compares strings character by character. It stops if a mismatch occurs or when the null character is reached, returning the difference in ASCII values.
A. strcmp() is efficient for comparing string content, especially for strcmp in C programming, as it stops once a mismatch is found, avoiding unnecessary comparisons.
A. strcmp() is case-sensitive by default. For case-insensitive comparisons, you can either convert both strings to lowercase or uppercase before comparing, or use stricmp() in some compilers.
A. Null-termination is crucial because strcmp in C programming relies on the null character (\0) to determine the end of the string. Without it, the function may read beyond the string's boundary, leading to undefined behavior.
A. When two strings are identical, strcmp() returns 0, indicating they are equal, as shown in strcmp in C with example.
A. strcmp() is useful in validating user inputs. For example, you can compare user input with expected strings to check if the input matches the required value, ensuring correct input.
A. No, strcmp() is specifically designed to compare strings (character arrays). If you need to compare different data types, you should convert them to strings before using strcmp in C programming.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.