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
String comparison in C is a core concept every C programmer needs to understand. Unlike modern languages where you can compare strings with ==, string comparison in C requires specific techniques because strings are stored as arrays of characters, not as high-level string objects.
In this blog, we'll explore different methods for string comparison in C, from using the standard strcmp() function to writing custom comparison logic with loops and pointers. Each method will be explained step by step, with code examples, comments, and output to help you follow along easily. Additionally, you should explore our software development courses to understand programming concepts in more efficient way.
By the end, you’ll not only know how to perform a string comparison in C, but also understand which method suits different programming scenarios. Whether you're comparing user input, sorting strings, or building more complex logic, this guide will make you confident in handling string comparison in C like a pro.
At its core, string comparison in C means checking whether two strings are the same or determining which one comes first in a lexicographical (dictionary) order. This is useful in countless situations, like comparing passwords, sorting names, or validating input.
But here's the thing: C doesn't treat strings as a built-in data type. Instead, strings in C are just arrays of characters ending with a null character (`'\0'`). Because of that, using the `==` operator doesn’t work for string comparison in C. Additionally, you should also learn about other operators in C to build your C program efficiently.
#include <stdio.h>
int main() {
char str1[] = "hello";
char str2[] = "hello";
if (str1 == str2) {
printf("Strings are equal.\n");
} else {
printf("Strings are not equal.\n");
}
return 0;
}
Output:
Strings are not equal.
Explanation:
In the above example, `str1 == str2` compares memory addresses—not the characters. So even if the content is the same, the result will say the strings are different. That’s why proper string comparison in C needs to go character by character or use dedicated functions.
To solve this, C offers multiple ways to handle string comparison:
Each method of string comparison in C has its own advantages, and we'll explore all of them in the upcoming sections. Understanding how these methods work under the hood helps avoid common pitfalls and bugs, especially in larger programs.
Boost your career journey with the following full-stack development courses:
There are several ways to perform string comparison in C, each suitable for different scenarios. Whether you're going for simplicity, performance, or deeper control over how the comparison works, C gives you multiple approaches to choose from.
Let’s look at the most common and effective methods used for string comparison in C:
The most common and reliable way to perform string comparison in C is by using the `strcmp()` function. This function is part of the C Standard Library and is defined in the `<string.h>` header.
Apart from this, you should also learn about the following functions in C to strengthen your foundational knowledge:
Syntax:
int strcmp(const char *str1, const char *str2);
Let’s look at a working example:
Example: Using `strcmp()` for String Comparison in C
#include <stdio.h>
#include <string.h> // Required for strcmp()
int main() {
char string1[] = "Apple";
char string2[] = "Banana";
// Perform string comparison in C using strcmp()
int result = strcmp(string1, string2);
if (result == 0) {
printf("The strings are equal.\n");
} else if (result < 0) {
printf("\"%s\" comes before \"%s\".\n", string1, string2);
} else {
printf("\"%s\" comes after \"%s\".\n", string1, string2);
}
return 0;
}
Output:
"Apple" comes before "Banana".
Step-by-Step Explanation:
1. We include `<string.h>` to access the `strcmp()` function.
2. We define two strings: `"Apple"` and `"Banana"`.
3. We use `strcmp(string1, string2)` to perform the string comparison in C.
4. Since `"Apple"` is lexicographically smaller than `"Banana"`, the result is a negative number.
5. Based on the result, we print the appropriate message.
Why Use `strcmp()` for String Comparison in C?
This makes it a go-to method for string comparison in C, especially for beginners or when you need a quick and simple solution.
If you want to perform string comparison in C without using the built-in `strcmp()` function, you can manually compare each character of the two strings. This method gives you more control and allows you to customize the comparison logic if needed.
How It Works:
You can loop through each string, comparing corresponding characters. The comparison stops as soon as a mismatch is found or when the end of either string (the null character `'\0'`) is reached. Before you move to the code example, you should explore our article on:
Let’s look at an example:
Example: Manual String Comparison in C
#include <stdio.h>
int compareStrings(char *str1, char *str2) {
while (*str1 && (*str1 == *str2)) {
str1++;
str2++;
}
return *(unsigned char *)str1 - *(unsigned char *)str2;
}
int main() {
char string1[] = "Apple";
char string2[] = "Apple";
int result = compareStrings(string1, string2);
if (result == 0) {
printf("The strings are equal.\n");
} else if (result < 0) {
printf("\"%s\" comes before \"%s\".\n", string1, string2);
} else {
printf("\"%s\" comes after \"%s\".\n", string1, string2);
}
return 0;
}
Output:
The strings are equal.
Step-by-Step Explanation:
1. The `compareStrings()` Function:
2. In `main()`:
Why Use Manual Comparison for String Comparison in C?
This method offers a deeper understanding of how strings work in C and is helpful when you need to build more advanced comparison functionality.
For more efficient or advanced string comparison in C, you can use pointers in C instead of array indexing. This method allows you to directly manipulate memory locations, which can sometimes lead to more performance-optimized code.
How It Works:
In C, strings are simply arrays of characters, and you can use pointers to traverse these arrays. By incrementing the pointers, you can compare each character in the string one by one, just like using array indexing, but with a more pointer-centric approach.
Here’s an example of string comparison in C using pointers:
Example: String Comparison in C Using Pointers
#include <stdio.h>
int compareStringsWithPointers(char *str1, char *str2) {
// Loop through both strings character by character using pointers
while (*str1 && (*str1 == *str2)) {
str1++; // Move to next character in str1
str2++; // Move to next character in str2
}
// Return the difference between the characters at the mismatch point
return *(unsigned char *)str1 - *(unsigned char *)str2;
}
int main() {
char string1[] = "Hello";
char string2[] = "Hello";
int result = compareStringsWithPointers(string1, string2);
if (result == 0) {
printf("The strings are equal.\n");
} else if (result < 0) {
printf("\"%s\" comes before \"%s\".\n", string1, string2);
} else {
printf("\"%s\" comes after \"%s\".\n", string1, string2);
}
return 0;
}
Output:
The strings are equal.
Step-by-Step Explanation:
1. The `compareStringsWithPointers()` Function:
2. In `main()`:
Why Use Pointers for String Comparison in C?
While this method is powerful and flexible, it's more advanced and requires a solid understanding of memory management and pointer arithmetic in C.
Below we have some additional C examples to thoroughly understand real-world applications of string comparison in C. Let’s explore them one by one.
A palindrome in C is a string that reads the same forward and backward (ignoring spaces, punctuation, and case). In this example, we will write a C program to check if a string is a palindrome by comparing characters from both ends of the string.
Example: Check If a String is a Palindrome
#include <stdio.h>
#include <string.h>
#include <ctype.h> // Required for tolower()
int isPalindrome(char *str) {
int start = 0;
int end = strlen(str) - 1;
while (start < end) {
// Skip non-alphanumeric characters
if (!isalnum(str[start])) {
start++;
} else if (!isalnum(str[end])) {
end--;
} else {
// Compare characters (case-insensitive)
if (tolower(str[start]) != tolower(str[end])) {
return 0; // Not a palindrome
}
start++;
end--;
}
}
return 1; // Is a palindrome
}
int main() {
char string[] = "A man, a plan, a canal, Panama";
if (isPalindrome(string)) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
Output:
The string is a palindrome.
Explanation:
This example demonstrates how to compare a string entered by the user with a predefined string, such as a password, and check if they match.
Example: Compare User Input with Predefined String
#include <stdio.h>
#include <string.h> // Required for strcmp()
int main() {
char userInput[50];
char correctPassword[] = "Secret123";
// Prompt user for input
printf("Enter your password: ");
fgets(userInput, sizeof(userInput), stdin);
// Remove newline character if present
userInput[strcspn(userInput, "\n")] = '\0';
// Compare the user input with the predefined password
if (strcmp(userInput, correctPassword) == 0) {
printf("Password is correct.\n");
} else {
printf("Password is incorrect.\n");
}
return 0;
}
Output (example):
Enter your password: Secret123
Password is correct.
Explanation:
Sometimes, you may want to compare two strings without considering the case of the characters. You can implement a custom function using `tolower()` or `toupper()` from `<ctype.h>`.
Example: Case-Insensitive String Comparison in C
#include <stdio.h>
#include <ctype.h> // Required for tolower()
int compareStringsCaseInsensitive(char *str1, char *str2) {
while (*str1 && (*str1 == *str2 || tolower(*str1) == tolower(*str2))) {
str1++;
str2++;
}
return *(unsigned char *)str1 - *(unsigned char *)str2;
}
int main() {
char string1[] = "Hello";
char string2[] = "hello";
int result = compareStringsCaseInsensitive(string1, string2);
if (result == 0) {
printf("The strings are equal (case-insensitive).\n");
} else {
printf("The strings are not equal (case-insensitive).\n");
}
return 0;
}
Output:
The strings are equal (case-insensitive)
Explanation:
The `compareStringsCaseInsensitive()` function compares two strings while ignoring their case. It uses `tolower()` to convert each character to lowercase before comparing.
Another common scenario is comparing only a portion (or substring) of a string. The standard `strncmp()` function can be used for string comparison in C up to a specific number of characters.
Example: Comparing Substrings in C
#include <stdio.h>
#include <string.h> // Required for strncmp()
int main() {
char string1[] = "Hello, World!";
char string2[] = "Hello, C Programming!";
// Compare the first 5 characters of both strings
if (strncmp(string1, string2, 5) == 0) {
printf("The first 5 characters of both strings are equal.\n");
} else {
printf("The first 5 characters of both strings are not equal.\n");
}
return 0;
}
Output:
The first 5 characters of both strings are equal.
Explanation:
`strncmp()` compares only the first 5 characters of the two strings. It stops at the specified length, making it useful when comparing prefixes or partial strings.
In this blog, we explored several techniques for string comparison in C, covering methods like using the strcmp() function, manual comparison through character-by-character checks, and utilizing pointers for efficient comparison. These methods are fundamental for various C programming tasks, such as verifying user input, comparing passwords, or checking if a string is a palindrome. Each approach offers flexibility depending on the scenario, from simple comparisons to more complex manipulations of strings.
Whether you're working with predefined strings or handling user input, mastering string comparison in C is essential for building robust applications. By understanding these techniques, you can better handle string operations, optimize your code, and ensure accurate results in real-world scenarios like authentication systems or text processing applications.
String comparison in C is the process of determining whether two strings are equal, or which one is lexicographically greater or smaller. C doesn't have a built-in string data type, so strings are typically arrays of characters. This makes string comparison crucial for tasks like sorting, searching, and validation in C programs.
The `strcmp()` function compares two strings character by character. It returns 0 if the strings are identical, a positive value if the first string is lexicographically greater, and a negative value if the first string is smaller. It stops comparing when it finds a mismatch or reaches the end of one of the strings.
Yes, strings in C can be compared manually by iterating over each character of both strings. You can use a loop to check if each character is the same. If you find a mismatch or reach the end of a string, you can conclude the comparison, returning values similar to `strcmp()` results.
For case-insensitive comparison in C, you can convert both strings to the same case (either lowercase or uppercase) using the `tolower()` or `toupper()` functions from the `<ctype.h>` library. After converting, you can compare the modified strings as usual, ensuring that differences in case don't affect the comparison result.
A palindrome is a word, phrase, or sequence that reads the same backward as forward. To check if a string is a palindrome in C, compare characters from both ends of the string. If all corresponding characters match, the string is a palindrome. Skip non-alphanumeric characters and check case-insensitively for a more robust solution.
To compare a substring in C, you can use `strncmp()`, which compares a specified number of characters from two strings. Another method involves manually iterating through the desired portion of the string and comparing it character by character. Ensure that the substring is of the same length for a valid comparison.
Yes, you can compare strings using pointers in C by directly accessing each character. Pointers allow you to traverse the strings efficiently by incrementing them and comparing characters one by one. This method is more memory-efficient than using array indexing and is often used in performance-critical applications.
To compare user input with a predefined string in C, use `fgets()` to capture the input, and remove any trailing newline character using `strcspn()`. Then, use `strcmp()` or a custom comparison function to compare the user-provided string to the predefined value. Ensure proper handling of input length and memory.
When comparing two strings of different lengths in C, `strcmp()` will return a non-zero value based on the first differing character. If the first string is shorter, it is considered lexicographically smaller, as `strcmp()` continues comparing characters until the null terminator of the shorter string, resulting in a difference.
Yes, you can compare strings without considering spaces by first removing or ignoring spaces. One approach is to loop through both strings, skipping over any spaces. Alternatively, you can use functions to remove spaces and then perform the comparison. This approach is useful for text normalization, such as matching phrases or codes.
The return value of `strcmp()` indicates the result of string comparison. If the strings are identical, it returns 0. If the first string is lexicographically smaller than the second, it returns a negative value. If the first string is greater, it returns a positive value. This return value helps determine the comparison outcome.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author|900 articles published
Previous
Next
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
+918068792934
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.