//Program to implement strcmp #includeint my_strcmp( const char *sDest, const char *sSrc){ while( *sDest == *sSrc){ if( *sDest == '\0') return 0; sDest++; sSrc++; } return (*sDest - *sSrc); } // OR int mystrcmp(const char *str1, const char *str2){ while((*str1 == *str2) && *str1 && *str2) str1++, str2++; return (*str1 - *str2); } //OR using array int mystrcmp(const char *a, const char *b) int i; for(i=0; (a[i] == b[i]) && (a[i] != '\0') && (b[i] != '\0'));i++); return (a[i] - b[i]) } int main(){ printf("\nstrcmp() = [%d]\n", mystrcmp("Umesh","Umesh")); printf("\nstrcmp() = [%d]\n", mystrcmp("Umesh","Guddu")); return(0); } ONE LINE IMPLEMENTATION USING RECURSION #include <stdio.h> //My_strcmp return 0 if both the string are same , 1 if they are diff int my_strcmp(char *a, char *b){ return (*a==*b && *b=='\0')?0:(*a == *b)?my_strcmp(++a, ++b):1; } int main(){ char *a = "Umesh"; char *b = "Umesh"; if(my_strcmp(a, b) == 0){ printf("Same"); else printf("Not same"); return 0; }
Thursday, 31 January 2013
STRCMP implementation in C
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment