strcmp() in C - Source Code Example

In this source code example, we will see how to use the strcmp() function in C programming with an example.

strcmp() Function Overview

The strcmp() function is a crucial function from the C standard library, included in the <string.h> header. It's primarily used to compare two strings lexographically. If both strings are identical, the function returns 0. If the first string is lexicographically less than the second one, it returns a negative value, and if it's greater, it returns a positive value. 

Key Points: 

- Located in the <string.h> header file. 

- Compares two strings character by character. 

- Return value can be: 

  •  0, if both strings are the same. 
  •  Negative, if the first string is less than the second. 
  •  Positive, if the first string is greater than the second.

Source Code Example


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

int main() {
    char string1[] = "apple";
    char string2[] = "banana";
    char string3[] = "apple";

    // Comparing two different strings
    if (strcmp(string1, string2) < 0) {
        printf("String1 comes before string2 lexicographically.\n");
    } else if (strcmp(string1, string2) > 0) {
        printf("String1 comes after string2 lexicographically.\n");
    } else {
        printf("String1 and string2 are the same.\n");
    }

    // Comparing two identical strings
    if (strcmp(string1, string3) == 0) {
        printf("String1 and string3 are the same.\n");
    }

    return 0;
}

Output

String1 comes before string2 lexicographically.
String1 and string3 are the same.

Explanation

1. We have declared three strings: string1, string2, and string3.

2. When comparing string1 and string2, since "apple" is lexicographically earlier than "banana", the output indicates that fact.

In the next comparison between string1 and string3, both are identical ("apple"), and the function confirms this with a return value of 0, resulting in the second printed message.


Comments