String Compare in C
Here you will get source code of String compare in c without using strcmp and String compare in c using strcmp function.
What will strcmp() function do
The strcmp() function is used to compare two strings, character by character in c programming. It returns zero if both strings are equal or non-zero if they are different.
It compares the two strings character by character until the end of string or any miss match found.
The strcmp() function works as described below.
It returns 0 if str1 and str2 are equal.
It return a negative value If str1 is less than str2.
It returns a positive value, If str1 is greater than str2.
String Compare in C using strcmp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | //strcmp program in C #include <stdio.h> #include <string.h> int main() { char a[100], b[100]; int result; printf("Input first string: "); gets(a); printf("Input second string: "); gets(b); result = strcmp(a, b); if (result < 0) printf("'%s' and '%s' strings are different\n", a, b); else if (result > 0) printf("'%s' and '%s' strings are different\n", a, b); else printf("'%s' and '%s' are equal string\n", a, b); return 0; } |
Output
String Compare in C without using strcmp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #include <stdio.h> int compareStr(char str1[], char str2[]) { int i = 0; while (str1[i] != '\0' || str2[i] != '\0') { if (str1[i] != str2[i]) { return 0; // Strings are not equal } i++; } if (str1[i] == '\0' && str2[i] == '\0') { return 1; // Strings are equal } return 0; // Strings are not equal } int main() { char str1[50]; char str2[50]; printf("Input first string: "); gets(str1); printf("Input second string: "); gets(str2); if (compareStr(str1, str2)) { printf("Both strings are equal... :)\n"); } else { printf("Both strings are not equal... :( \n"); } return 0; } |
Output
Input first string: CodeRevise
Input second string: Coderevise.com
Both strings are not equal… 🙁
Input first string: learn coding
Input second string: learn coding
Both strings are equal… 🙂
Check out our other C programming Examples