top

Search

C Tutorial

.

UpGrad

C Tutorial

Strcmp in C

The C programming language, known for its wide-ranging flexibility and low-level capabilities, offers a plethora of in-built functions, among which, the string handling functions play a crucial role. One such function is the strcmp() in C. This article explores the anatomy of strcmp(), its parameters, syntax, and the return value it provides when used in a program.

Introduction

In C, a string is an array of characters terminated by a null character ('\0'). While handling strings, comparing two strings is a common operation. For instance, string comparison is vital in sorting, searching operations, or even in login systems where we compare the input password with the stored password. strcmp() function is a handy tool for such situations. This article elucidates this function, its usage, syntax, and strcmp example.

What is strcmp() in C?

strcmp() stands for "string compare". It is a built-in function in C, included in the string.h library. The primary role of this function is to compare two strings lexicographically. The comparison is based on ASCII values of the characters.

Syntax of strcmp() in C

The syntax of the strcmp() function is simple and easy to understand. It's as follows:

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

Here, str1 and str2 are the two strings that need to be compared.

Parameters of strcmp() in C

The strcmp() in C takes two parameters:

1. str1 – the first string for comparison.

2. str2 – the second string to be compared with the first string.

Both str1 and str2 are pointers to the first characters of the strings to be compared.

strcmp() Prototype

The prototype for the strcmp() function in the C library is:

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

It returns an integer value after comparison, which leads us to the next section, strcmp return value in c.

Return Value of strcmp() in C

The strcmp() function returns an integer that can tell you whether the strings are equal and which one would come first in a dictionary. The value returned by strcmp() depends on the ASCII values of the characters in the strings.

Let's elaborate on each case:

Zero: This return value signifies that both strings are equal. This means every corresponding pair of characters in the two strings is the same.

Example:

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Hello";
    char str2[] = "Hello";

    int result = strcmp(str1, str2);

    printf("Return value: %d\n", result);
    return 0;
}

Output: Return value: 0

Positive Value: A positive return value indicates that the first string (str1) is greater than the second string (str2). The positive value is the difference between the ASCII value of the character where the difference was first spotted.

Example:

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "HelloZ";
    char str2[] = "HelloA";

    int result = strcmp(str1, str2);

    printf("Return value: %d\n", result);
    return 0;
}

Output: Return value: 25 (Here, 'Z' has the ASCII value 90 and 'A' has 65. Thus, 90-65=25)

Negative Value: A negative return value represents that the first string (str1) is less than the second string (str2). The negative value is the difference between the ASCII value of the character where the difference was first spotted.

Example:

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "HelloA";
    char str2[] = "HelloZ";

    int result = strcmp(str1, str2);

    printf("Return value: %d\n", result);
    return 0;
}

Output: Return value: -25 (Here, 'A' has the ASCII value 65 and 'Z' has 90. Thus, 65-90=-25)

Please note that the strcmp() function is case-sensitive. It treats uppercase and lowercase characters as different, as they have different ASCII values. If you want to compare strings in a case-insensitive way, you can use the strcasecmp() function instead.

How to use the strcmp() function in C

The strcmp() function in C provides a straightforward way to compare two strings. The steps below outline how to use this function in your code:

Include the Header File: strcmp() is part of the string.h header file. So, the first step is to include this header in your C program. This is done using the #include directive as shown below:

#include <string.h>

Declare Strings: Next, declare the strings that you want to compare. Strings in C are essentially arrays of characters terminated by a null character ('\0'). Here's an example of how to declare two strings:

char str1[] = "upGrad";
char str2[] = "upGrad Tutorials";

Use strcmp(): Now you can use strcmp() to compare the two strings. Pass the strings as arguments to strcmp(). It will compare both strings lexicographically and return an integer based on the comparison.

int result = strcmp(str1, str2);

Process the Result: Based on the return value, you can determine whether the two strings are equal or which one is greater. A common way to handle this is through an if-else statement, as shown:

if(result == 0) {
    printf("Strings are equal.\n");
} else if(result < 0) {
    printf("str1 is less than str2.\n");
} else {
    printf("str1 is greater than str2.\n");
}

Here's a complete example that puts it all together:

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "OpenAI";
    char str2[] = "OpenAI GPT-4";

    int result = strcmp(str1, str2);

    if(result == 0) {
        printf("Strings are equal.\n");
    } else if(result < 0) {
        printf("str1 is less than str2.\n");
    } else {
        printf("str1 is greater than str2.\n");
    }

    return 0;
}

How strcmp() in C works

The strcmp() function in C works by performing a lexicographic comparison, which is similar to how words are arranged in a dictionary. The function begins by comparing the first character from each of the two strings. If these characters are equal, it proceeds to the next pair. This process continues until it encounters a pair of characters that aren't equal or until it reaches the end of one or both strings (a null character '\0').

Let's dive a bit deeper into its working mechanism:

1. Character by Character Comparison: The function starts comparing the first character of each string. If they are equal, it moves to the next characters of the strings. strcmp() compares the ASCII values of each pair of characters from str1 and str2.

2. First Mismatch or Null Character: The comparison process stops when it encounters a pair of characters that aren't equal or a null character '\0' which signifies the end of a string.

3. Determining the Result: If it finds a pair where the character from str1 is not equal to the character from str2, it subtracts the ASCII value of the character in str2 from the ASCII value of the character in str1 and returns this value. If no such pair is found (meaning the strings are equal until the end of one or both strings), it subtracts the length of str2 from the length of str1 and returns this value.

To put it in simpler terms:

  • The function compares the characters of the two strings one by one, starting from the first character.

  • It compares the ASCII values of the characters. If the ASCII value of the character in the first string is greater than the corresponding character in the second string, it returns a positive value. If the ASCII value is smaller, it returns a negative value.

  • The comparison continues until a difference is found or one of the strings ends.

  • If both strings are identical (i.e., all characters are equal), it returns 0.

Thus, strcmp() helps determine not only whether the two strings are equal but also, if they aren't, which one would come first in lexicographical (dictionary) order.

Examples of strcmp() in C

Using strcmp() in C, you can compare two strings and determine whether they are the same or which one would come first in a dictionary. Let's consider some examples to see this in action.

Example 1: Two Equal Strings

#include <stdio.h>
#include <string.h>

int main() {
    char Inputstr1[] = "Upgrad";
    char Inputstr2[] = "Upgrad";

    int result = strcmp(Inputstr1, Inputstr2);

    if(result == 0) {
        printf("Strings are equal.\n");
    } else {
        printf("Strings are not equal.\n");
    }

    return 0;
}

In this program, the strcmp() function compares Inputstr1 and Inputstr2. As both are the same, it returns 0, and the program outputs "Strings are equal."

Example 2: str1 is Lexicographically Less than str2

#include <stdio.h>
#include <string.h>

int main() {
    char Inputstr1[] = "Upgrad";
    char Inputstr2[] = "Upgradation";

    int result = strcmp(Inputstr1, Inputstr2);

    if(result < 0) {
        printf("str1 is lexicographically less than str2.\n");
    } else {
        printf("str1 is not lexicographically less than str2.\n");
    }

    return 0;
}

Here, str1 is lexicographically less than str2. strcmp() will return a negative value, and the output will be "str1 is lexicographically less than str2."

Example 3: str1 is Lexicographically Greater than str2

#include <stdio.h>
#include <string.h>

int main() {
    char Inputstr1[] = "UpgradZ";
    char Inputstr2[] = "UpgradA";

    int result = strcmp(Inputstr1, Inputstr2);

    if(result > 0) {
        printf("str1 is lexicographically greater than str2.\n");
    } else {
        printf("str1 is not lexicographically greater than str2.\n");
    }

    return 0;
}

In this example, str1 is lexicographically greater than str2, so strcmp() will return a positive value. The output will be "str1 is lexicographically greater than str2."

Conclusion

The strcmp() function is an efficient way to compare two strings in c. It provides an easy-to-use interface for comparing strings lexicographically. However, in some cases, you might want to string compare in C without using strcmp(). In those instances, you can make use of loops and conditionals, though it requires a bit more work.

Understanding such intrinsic details of strcmp() in C enriches your programming knowledge and skills. As a part of your learning journey, consider checking out upGgrad's Master of Science in Data Science program,  offered under the guidance of Liverpool John Moores University. This course will surely bolster your coding abilities and broaden your horizons in the tech industry.

FAQs

1. Can strcmp() be used to compare strings of different lengths?

Yes, strcmp() can compare strings of different lengths. It keeps comparing corresponding characters of both the strings until it encounters a null character.

2. How does strcmp() compare strings lexicographically?

strcmp() compares strings character by character using their ASCII values. The comparison stops as soon as a difference is found or one of the strings ends.

3. What's the difference between strcmp() and strcpy() in C?

While both strcmp() and strcpy() are built-in functions in C for handling strings, they serve different purposes. strcmp() is used to compare two strings lexicographically, and it returns an integer based on the comparison. On the other hand, strcpy() is used to copy one string into another. It doesn't perform any comparison but rather duplicates the contents of a string.

Leave a Reply

Your email address will not be published. Required fields are marked *