Sunday 31 August 2014

C Function to compare two strings

This is a C function to compare two strings. The function takes two strings as arguments, loops while the characters in both the string are equal and the end of either string is not reached.  After finishing the loop, it returns the difference of ASCII values (string1[i] - string2[i]) of the characters where the loop is stopped. 

So the final value may be:
          -ve, if string 1 is less than string 2
          +ve, if string 1 is greater than string 2
           0 , if both the strings are same

Source Code

# include <stdio.h>
# include <conio.h>

/* Function definition */
int cmpstr (char str1 [], char str2[] ) {
    int i, diff;

    for (i=0;str1[i]==str2[i] && str1[i]!=0 && str2[i]!=0;i++);
    diff = str1[i]-str2[i];

    return diff;

int main() {
    char str1[30], str2[30];
    int diff;


    printf("Enter a string:");
    scanf("%s", str1);
    printf("Enter another string:");
    scanf("%s", str2);

    diff=cmpstr(str1, str2); // Function Call

    if (diff<0)
        printf("\n\nstring 1 (%s) is less than string 2 (%s)", str1, str2);
    else if (diff==0)
        printf("\n\nstring 1 (%s) and  string 2 (%s) are same", str1, str2);
        printf("\n\nstring 1 (%s) is greater than string 2 (%s)", str1, str2);

    return 0;


String1 is less than String2

String1 is greater than String2

String1 and  String2 are same

No comments:

Post a Comment