# Comparing strings

A program to compare strings:

```c
#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:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1712121934860/a2950be5-f0a6-4022-8b9d-45f10d7e0ac2.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1712121984343/a3b0d1f8-fe84-4b3c-801d-ff3f77ee918e.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1712122017754/d3f54725-c166-41fc-8b80-4c2af265e957.png align="center")

### Modularizing it with a user-defined function to compare strings

```c
#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:

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

## Return Value from strcmp()

| Return Value | Remarks |
| --- | --- |
| 0 | if strings are equal |
| \&gt;0 | if the first non-matching character in str1 is greater (in ASCII) than that of str2. |
| &lt;0 | if the first non-matching character in str1 is lower (in ASCII) than that of str2. |

```c
#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
