Saturday 4 February 2017

Write a program to compare two strings without using strcmp() function


We have to write our own string comparison function


int own_strcmp(const char *str1, const char *str2)
{
        int i=0;
        while(str1[i] && str2[i]){
                if( str1[i] != str2[i]){
                        break;
                }
                i++;
        }
        return str1[i]-str2[i];
}

Full Code


#include <stdio.h>
int own_strcmp(const char *str1, const char *str2)
{
        int i=0;
        while(str1[i] && str2[i]){
                if( str1[i] != str2[i]){
                        break;
                }
                i++;
        }
        return str1[i]-str2[i];
}

int main(int argc, char *argv[]){
        printf("%s and %s is %d\n", argv[1], argv[2], own_strcmp(argv[1], argv[2]));
        return 0;
}

Compilation and Output


rajesh@ideapad:~/Rajesh/Blog/string$ gcc own_strcmp.c
rajesh@ideapad:~/Rajesh/Blog/string$ ./a.out hello hello
hello and hello is 0
rajesh@ideapad:~/Rajesh/Blog/string$ ./a.out hello hello1
hello and hello1 is -49
rajesh@ideapad:~/Rajesh/Blog/string$ ./a.out hello12 hello1
hello12 and hello1 is 50

No comments:

Post a Comment