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
View All
View All
View All
View All
View All
View All
View All
View All
View All

Strcmp in C

Updated on 05/02/20253,705 Views

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!

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.

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: helloEnter second string: helloThe strings are equal.
Enter first string: helloEnter second string: worldThe 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:BananaAppleCherryMangoPineapple
After sorting:AppleBananaCherryMangoPineappleeapple

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.

How Well Do You Know strcmp in C? 10 Clever MCQs

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.

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?

A. 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?

A. 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?

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.

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

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.

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

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.

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

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.

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

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.

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

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.

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

A. 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?

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.

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

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.

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

+918045604032

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.