Skip to main content

Command Palette

Search for a command to run...

Comparing strings

Published
2 min readView as Markdown

A program to compare strings:

#include <stdio.h>
#define MAX 50

int main(){
    char str1[MAX];
    printf("Enter the string:");
    fgets(str1,MAX,stdin);
    printf("\nThe first string is %s",str1);
    char str2[MAX];
    printf("Enter the string:");
    fgets(str2,MAX,stdin);
    printf("\nThe second string is %s",str2);
    int i=0,diff=0;
    while(str1[i]!='\0' && str2[i]!='\0' && !diff){
              diff=str1[i]-str2[i];
              i++;
    }

    if(diff<0) printf("\n The strings are in dictionary order.");
    else if (diff == 0) printf("\n Both the strings are the same.");
    else printf("\n The strings are not in dictionary order.");
}

Output:

Modularizing it with a user-defined function to compare strings

#include <stdio.h>
#define MAX 50
int myStrCmp(char str1[],char str2[]){
    int i=0,diff=0;
    while(str1[i]!='\0' && str2[i]!='\0' && !diff){
              diff=str1[i]-str2[i];
              i++;
    }
    return diff;
}
int main(){
    char str1[MAX];
    printf("Enter the string:");
    fgets(str1,MAX,stdin);
    printf("\nThe first string is %s",str1);
    char str2[MAX];
    printf("Enter the string:");
    fgets(str2,MAX,stdin);
    printf("\nThe second string is %s",str2);

    int diff = myStrCmp(str1,str2);

    if(diff<0) printf("\n The strings are in dictionary order.");
    else if (diff == 0) printf("\n Both the strings are the same.");
    else printf("\n The strings are not in dictionary order.");
}

Output remains the same.

Using strcmp() from string.h library

The function prototype of strcmp() is:

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

Return Value from strcmp()

Return ValueRemarks
0if strings are equal
\>0if the first non-matching character in str1 is greater (in ASCII) than that of str2.
<0if the first non-matching character in str1 is lower (in ASCII) than that of str2.
#include <stdio.h>
#include <string.h>
#define MAX 50

int main(){
    char str1[MAX];
    printf("Enter the string:");
    fgets(str1,MAX,stdin);
    printf("\nThe first string is %s",str1);
    char str2[MAX];
    printf("Enter the string:");
    fgets(str2,MAX,stdin);
    printf("\nThe second string is %s",str2);

    int diff = strcmp(str1,str2);

    if(diff<0) printf("\n The strings are in dictionary order.");
    else if (diff == 0) printf("\n Both the strings are the same.");
    else printf("\n The strings are not in dictionary order.");
}

Output remains the same

19 views

More from this blog

P

Programming Tutorials

89 posts