📝⚡Beginner
Compare Two Strings
Compare strings
Compare two strings character by character. Returns 0 if equal, negative if str1 < str2, positive if str1 > str2.
Program Code
string_compare.c
C
1#include <stdio.h>23int stringCompare(char str1[], char str2[]) {4 int i = 0;5 while (str1[i] != '\0' && str2[i] != '\0') {6 if (str1[i] != str2[i]) {7 return str1[i] - str2[i];8 }9 i++;10 }11 return str1[i] - str2[i];12}1314int main() {15 char str1[50], str2[50];16 17 printf("Enter first string: ");18 scanf("%49s", str1);19 printf("Enter second string: ");20 scanf("%49s", str2);21 22 int result = stringCompare(str1, str2);23 24 if (result == 0)25 printf("Strings are equal\n");26 else if (result < 0)27 printf("\"%s\" comes before \"%s\"\n", str1, str2);28 else29 printf("\"%s\" comes after \"%s\"\n", str1, str2);30 31 return 0;32}Output
Enter first string: apple
Enter second string: banana
"apple" comes before "banana"
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials