Comparing two strings is a fundamental operation in programming, allowing us to determine whether two sequences of characters are the same or not. In C, strings are arrays of characters, and comparing them involves comparing each character of the arrays.
There are multiple ways to perform string comparison in C programming and here we are going to learn each of them.
String Comparison Using Loop.
We can manually compare each character of the two strings using a loop. This approach gives you more control and is useful when you need to implement custom comparison logic.
C Code:
// C Program to compare two string using loop #include <stdio.h> #include <string.h> int main() { char str1[] = "Apple"; char str2[] = "Apples"; int i = 0; //comparing two string char by char while (str1[i] != '\0' && str2[i] != '\0') { if (str1[i] != str2[i]) { printf("The strings are not equal.\n"); return 0; } i++; } if (str1[i] == '\0' && str2[i] == '\0') { printf("The strings are equal.\n"); } else { printf("The strings are not equal.\n"); } return 0; }
The strings are not equal.
String Comparison Using strcmp() Function.
- If the return value is 0, it means the strings are equal.
- If the return value is negative, it means the first string (str1 in our case) is less than the second string (str2).
- If the return value is positive, it means the first string is greater than the second string.
// C Program to compare two string using strcmp #include <stdio.h> #include <string.h> int main() { char str1[] = "Hello"; char str2[] = "Hello"; //built-in function to compare string int result = strcmp(str1, str2); if (result == 0) { printf("The strings are equal.\n"); } else if (result < 0) { printf("str1 is less than str2.\n"); } else { printf("str1 is greater than str2.\n"); } return 0; }
The strings are equal.
No comments:
Post a Comment