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

strcmp in C: How to Compare Strings with Examples

Updated on 03/06/20253,930 Views

Why does strcmp("hello", "Hello") return a non-zero value in C?

Because the strcmp function checks every character—case and all.

The strcmp in C function is used to compare two strings character by character. It returns 0 if both strings are equal, a positive value if the first string is greater, and a negative value if it’s smaller. This makes it essential in sorting strings, validating input, and implementing search operations.

In this tutorial, you’ll learn how strcmp in C works, how to interpret its return values, and when to use it in real programs. We’ll walk through simple examples to show what happens when strings match, differ by case, or have different lengths.

By the end, you’ll have a clear understanding of how to compare strings effectively in C. Want to strengthen your command of C programming and core concepts? Explore our Software Engineering Courses to build practical skills that matter.

What is strcmp() in C?

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.

Syntax of strcmp() in C

The general syntax of the strcmp() function is as follows:

int strcmp(const char *str1, const char *str2);

Let’s break it down:

  • int: The return type is an integer, which indicates the result of the comparison.
  • *const char str1: This is the first string you want to compare. It’s a constant character pointer (const char *), meaning it points to the string's first character.
  • *const char str2: This is the second string to compare with the first string, also a const char *.
  • Both strings must be null-terminated, meaning the last character is the NULL character ('\0'), marking the end of the string.

You’ve done great mastering the fundamentals of C! Why not take the next step and dive deeper into today’s most sought-after technologies? Here are three impactful options:

strcmp() Prototype

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.

Return Value of strcmp() in C

Let’s break down what the return value means:

  • 0: If both strings are identical (i.e., they have the same characters in the same order), the function will return 0. This indicates that the strings are equal.
  • < 0: If the first string (str1) is lexicographically less than the second string (str2), it returns a negative value. This means str1 is alphabetically smaller than str2.
  • > 0: If str1 is lexicographically greater than str2, it returns a positive value. This means str1 comes after str2 in the alphabet.

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.

How to Use the strcmp() Function in C

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

Enter second string: hello

The strings are equal.

Enter first string: hello

Enter second string: world

The strings are not equal.

Explanation:

  1. User Input:
    • We use fgets() to safely get the input from the user. fgets() reads the input string and stores it in the str1 and str2 arrays.
    • strcspn() is used to remove the newline character that fgets() might append when the user presses Enter.
  2. strcmp() Function:
    • The strcmp() function is called to compare str1 and str2. If the two strings are equal, strcmp() returns 0. If they differ, it returns a non-zero value.
  3. Equality Check:
    • If strcmp(str1, str2) == 0, we print "The strings are equal." Otherwise, we print "The strings are not equal."

Let’s dive into how strcmp() works under the hood.

How strcmp in C Programming Works

Here's the step-by-step breakdown of how it works:

  • Character-by-Character Comparison:
    • strcmp() compares the characters of the two strings at the same position, starting from the first character (index 0).
    • If the characters match, it moves to the next character and continues comparing.
    • Example: When comparing "hello" and "hello", strcmp() compares 'h' with 'h', 'e' with 'e', and so on, until both strings reach the null character ('\0'), confirming the strings are identical.

 "hello", strcmp()

  • Difference Between ASCII Values:
    • When strcmp() encounters a mismatch, it stops and returns the difference between the ASCII values of the mismatched characters.
    • Example: For the comparison between "apple" and "orange", the first mismatch is found between 'a' (ASCII 97) and 'o' (ASCII 111). strcmp() calculates the difference (97 - 111) and returns -14.

 "hello", strcmp() apple

Stopping Condition:

  • If one string is shorter than the other, strcmp() stops when it reaches the null character ('\0') in the shorter string.
  • Example: In comparing "bat" and "battery", strcmp() stops when it reaches the null character in "bat" and calculates the difference between 't' (ASCII 116) and '\0' (ASCII 0), returning -116.

strcmp battery

Why Use strcmp() Instead of Relational Operators?

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:

  • Relational Operators (==, <, >): When you use relational operators like == to compare strings, you're comparing pointer values, not the actual content of the strings. This can lead to incorrect results, especially if the strings are stored in different memory locations.
  • strcmp(): strcmp() compares the strings character by character, ensuring that the strings' actual content is being compared, not just their memory addresses.

Key Takeaways:

  • strcmp() compares two strings character by character, returning 0 if they are equal and a non-zero value if they differ.
  • It’s more reliable than using relational operators for string comparison because it compares the actual content, not the memory addresses.
  • By mastering strcmp() in C programming, you'll be able to perform more precise string comparisons for tasks like sorting, searching, and validating user input.

Also Read: How to Implement Selection Sort in C?

Now that you know how strcmp() works, let's explore some examples.

Examples of strcmp() in C

These examples will help you understand how to handle case sensitivity, and even use strcmp() for sorting strings lexicographically.

Let’s dive into it!

Example 1: Case Sensitivity in String Comparison

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:

  • strcmp() returns a non-zero value (32 in this case) because the ASCII values of 'a' (97) and 'A' (65) are different.
  • strcmp() considers case-sensitive differences, so "apple" and "Apple" are not equal.

Example 2: Sorting Strings Lexicographically

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:

Banana

Apple

Cherry

Mango

Pineapple

After sorting:

Apple

Banana

Cherry

Mango

Pineapple

Explanation:

  • The bubbleSort() function sorts the array of strings using strcmp().
  • The comparison strcmp(arr[j], arr[j + 1]) > 0 checks if the strings are out of order and swaps them if necessary.
  • strcmp() helps in comparing and sorting two strings lexicographically, which is key in organizing data like names, product lists, or search results.

Key Takeaways:

  • strcmp() is case-sensitive and compares strings character by character.
  • strcmp() returns 0 when the strings are equal, a positive value when the first string is greater, and a negative value when the first string is smaller.
  • It is useful for tasks like string comparison, sorting, and handling case sensitivity.

Let’s move on to some common errors you should be aware of.

Common Errors and Pitfalls in Using strcmp()

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:

1. Not Handling Null-Terminated Strings Properly

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:

  • In this case, str2 has a trailing space, which is not properly null-terminated. strcmp() will compare characters beyond the actual string and return that the strings are not equal.
  • Always ensure your strings are properly null-terminated, especially when dealing with user input.

2. Confusing String Comparison with Pointer Comparison

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:

  • Here, str1 and str2 are two separate arrays of characters. Even though the content is the same, == compares the memory addresses, and since the arrays are stored in different locations, it returns false.
  • Always use strcmp() to compare the content of two strings, not ==.

Avoiding these common pitfalls, you can effectively use strcmp in your C programming projects.

MCQs on strcmp in C

1. What is the purpose of strcmp() in C?

a) Copy one string to another

b) Compare two strings

c) Reverse a string

d) Concatenate strings

2. Which header file is required to use strcmp()?

a) stdio.h

b) stdlib.h

c) string.h

d) math.h

3. What is the return type of strcmp()?

a) char

b) int

c) void

d) bool

4. What does strcmp("abc", "abc") return?

a) 1

b) -1

c) 0

d) NULL

5. What is the return value of strcmp("abc", "abd")?

a) 0

b) Positive value

c) Negative value

d) Error

6. What does a negative return value from strcmp(a, b) indicate?

a) a is greater than b

b) a is equal to b

c) a is less than b

d) a is NULL

7. Which of these comparisons is case-sensitive in C?

a) str1 == str2

b) strcmp(str1, str2)

c) str1 != str2

d) str1 equals str2

8. What happens if one of the strings in strcmp() is NULL?

a) Returns 0

b) Always returns -1

c) Causes undefined behavior or segmentation fault

d) Returns true

9. A student writes if(strcmp(str1, str2)) but it behaves unexpectedly when strings match. Why?

a) strcmp returns a pointer

b) strcmp returns 0 when strings match

c) Condition is incorrect

d) Both b and c

10. You are sorting an array of strings alphabetically. Which function should be used for comparison in qsort()?

a) strcmp()

b) strlen()

c) strcpy()

d) scanf()

11. Your interviewer asks how strcmp() works internally. What's the best answer?

a) It compares string lengths

b) It compares characters one by one using ASCII values

c) It converts strings to integers

d) It only checks the first character

How Can upGrad Help You Master C Programming?

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?

FAQs

1. What is the difference between strcmp() and == when comparing strings in C?

The strcmp in C programming function compares string content character by character, while == compares memory addresses, leading to incorrect results for string comparison.

2. How does strcmp() handle case sensitivity?

strcmp in C programming is case-sensitive. It considers "apple" and "Apple" different due to ASCII value differences between lowercase and uppercase characters.

3. Can strcmp() be used for sorting strings?

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.

4. What happens if the strings being compared by strcmp() are of different lengths?

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.

5. How does strcmp() work internally when comparing strings?

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.

6. Is there any performance advantage of using strcmp() over other string comparison methods?

strcmp() is efficient for comparing string content, especially for strcmp in C programming, as it stops once a mismatch is found, avoiding unnecessary comparisons.

7. Can strcmp() be used to compare strings in a case-insensitive manner?

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.

8. Why is it necessary to null-terminate strings when using strcmp()?

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.

9. What is the return value of strcmp() when the strings are equal?

When two strings are identical, strcmp() returns 0, indicating they are equal, as shown in strcmp in C with example.

10. How can strcmp() be used for string validation in C?

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.

11. Can I compare strings of different data types using strcmp()?

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.

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.