C Programming Code Examples C > Strings Code Examples C program to compare two strings C program to compare two strings Write a C program to compare two strings using loop character by character. How to compare two strings without using inbuilt library function strcmp() in C programming. Comparing two strings lexicographically without using string library functions. How to compare two strings using strcmp() library function. Logic to compare two strings Input two strings from user. Store it in some variable say str1 and str2. Compare two strings character by character till an unmatched character is found or end of any string is reached. If an unmatched character is found then strings are not equal. Else if both strings reached their end then both strings are equal. #include <stdio.h> #define maxsize 100 // Maximum string size /* Compare function declaration */ int compare(char * str1, char * str2); int main() { char str1[maxsize], str2[maxsize]; int res; /* Input two strings from user */ printf("Enter first string: "); gets(str1); printf("Enter second string: "); gets(str2); /* Call the compare function to compare strings */ res = compare(str1, str2); if(res == 0) { printf("Both strings are equal."); } else if(res < 0) { printf("First string is lexicographically smaller than second."); } else { printf("First string is lexicographically greater than second."); } return 0; } /** * Compares two strings lexicographically. * Returns 0 if both strings are equal, * negative if first string is smaller * otherwise returns a positive value */ int compare(char * str1, char * str2) { int j = 0; /* Iterate till both strings are equal */ while(str1[j] == str2[j]) { if(str1[j] == '\0' && str2[j] == '\0') break; j++; } // Return the difference of current characters. return str1[j] - str2[j]; }