View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Comprehensive Guide to String Comparison in C

Updated on 05/05/20254,037 Views

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.

What is String Comparison in C?

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. 

Example: Why `==` Doesn’t Work

#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:

  • Using standard library functions like `strcmp()`
  • Manually comparing characters in a loop
  • Using pointers for more control 

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: 

Methods to Perform String Comparison in C

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:

1) String Comparison in C Using `strcmp()`

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);

  • Returns `0` if both strings are equal.
  • Returns a positive value if `str1` is greater than `str2`.
  • Returns a negative value if `str1` is less than `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?

  • It’s reliable and standard across platforms.
  • It saves you from writing custom loops.
  • It’s readable and easy to maintain.

This makes it a go-to method for string comparison in C, especially for beginners or when you need a quick and simple solution.

2) String Comparison in C Without `strcmp()`

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:

  • We use a `while` loop to compare each character in both strings. The loop continues as long as both characters are the same and the current character is not the null character (`'\0'`).
  • If we encounter a mismatch or reach the end of one string, the function returns the difference between the ASCII values of the characters at the current position. This mimics the behavior of `strcmp()`.

2. In `main()`:

  • We define two strings: `"Apple"` and `"Apple"`.
  • We call the `compareStrings()` function to compare them.
  • Based on the result, we print whether the strings are equal, or if one comes before or after the other.

Why Use Manual Comparison for String Comparison in C?

  • You can customize the comparison logic, such as ignoring case or handling specific character sets.
  • It helps you understand the underlying mechanics of string comparison in C.
  • In certain cases (e.g., when working with embedded systems or very large datasets), manual string comparison can be optimized to better suit your needs.

This method offers a deeper understanding of how strings work in C and is helpful when you need to build more advanced comparison functionality.

3) String Comparison in C Using Pointers

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:

  • We use two pointers, `str1` and `str2`, to traverse the strings character by character.
  • The `while` loop continues as long as both characters pointed to by `str1` and `str2` are the same, and neither string has reached the null terminator (`'\0'`).
  • Once a mismatch is found, the difference between the two characters is returned, which is similar to the behavior of `strcmp()`.

2. In `main()`:

  • We define two identical strings: `"Hello"` and `"Hello"`.
  • The function `compareStringsWithPointers()` is called to compare them.
  • Depending on the result, the program prints whether the strings are equal, or if one comes before or after the other.

Why Use Pointers for String Comparison in C?

  • Pointers allow direct memory access, which can make the code more efficient, especially in performance-critical applications.
  • Using pointers gives you more control over the memory and can be useful for complex string manipulation tasks.
  • Pointers can be easily adapted for tasks like comparing substrings or handling special cases (e.g., ignoring certain characters).

While this method is powerful and flexible, it's more advanced and requires a solid understanding of memory management and pointer arithmetic in C.

Additional Examples of String Comparison 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. 

1) Check If a String is a Palindrome in C

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:

  • The `isPalindrome()` function compares characters from both ends of the string.
  • It skips non-alphanumeric characters and performs a case-insensitive comparison of the remaining characters.
  • The function returns `1` if the string is a palindrome and `0` if it's not.

2) Compare User Input with Predefined String in C

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:

  • We use `fgets()` to read the user input, allowing for spaces in the password.
  • The newline character (if present) is removed using `strcspn()`.
  • `strcmp()` compares the user input to the predefined password (`"Secret123"`) and outputs whether the password is correct or incorrect.

3) Case-Insensitive String Comparison in C

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.

4) Comparing Substrings in C

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.

Conclusion

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.

FAQs

1. What is string comparison in C?

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.

2. How does `strcmp()` work in C?

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.

3. Can we compare strings in C without `strcmp()`?

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.

4. How do you compare strings case-insensitively in C?

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.

5. What is a palindrome and how can we check it in C?

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.

6. How do we compare a substring of a string in C?

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.

7. Can we compare strings using pointers in C?

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.

8. How do I compare user input to a predefined string in C?

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.

9. What happens when you compare two strings with different lengths in C?

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.

10. Is it possible to compare strings without considering spaces in C?

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.

11. What is the return value of `strcmp()` in C?

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.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

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.