Q:

C program to compare strings using strcmp() function

belongs to collection: C String Programs

0

C program to compare strings using strcmp() function

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to check a string is palindrome or not w... >>
<< Write your own memset() function in C...