C program to compare strings using strcmp() function

C language strcmp() function example: Here, we are going to learn how to compare two strings using strcmp() function in C programming language?
Submitted by Sanjeev, on April 11, 2019

Given two strings and we have to compare them using strcmp() function in C language.

C language strcmp() function

strcmp() function is used to compare two stings, it checks whether two strings are equal or not.

strcmp() function checks each character of both the strings one by one and calculate the difference of the ASCII value of the both of the characters. This process continues until a difference of non-zero occurs or a \0 character is reached.

Return value

Return value/result of strcmp() function:

  • 0 : If both the strings are equal
  • Negative : If the ASCII value of first unmatched character of first string is smaller than the second string
  • Positive : If the ASCII value of first unmatched character of first character is greater than the second string

C program to compare strings using strcmp()

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

int main(){
    char str1[] = "Includehelp", str2[] = "includehelp", str3[] = "Includehelp";
    int res = 0, cmp = 0;

    // Compares string1 and string2 and return the difference
    // of first unmatched character in both of the strings
    // unless a '\0'(null) character is reached.
    res = strcmp(str1, str2);

    if (res == 0)
        printf("\n %s and %s are equal\n\n", str1, str2);
    else
        printf("\n %s and %s are not equal\n\n", str1, str2);

    // Compares string1 and string3 and return the difference
    // of first unmatched character in both of the strings
    // unless a '\0'(null) character is reached.
    cmp = strcmp(str1, str3);

    if (cmp == 0)
        printf(" %s and %s are equal\n\n", str1, str3);
    else
        printf(" %s and %s are not equal\n\n", str1, str3);

    return 0;
}

Output

Includehelp and includehelp are not equal

 Includehelp and Includehelp are equal

C String Programs »

Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.