Home » C programs

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/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/example for strcmp() function

#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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.