The Program in C to Compare two strings using pointers is given below:
#include <stdio.h>
int string_compare(char *str1, char *str2) {
while (*str1 != '\0' && *str2 != '\0') {
if (*str1 != *str2) {
return *str1 - *str2;
}
str1++;
str2++;
}
if (*str1 == '\0' && *str2 == '\0') {
return 0;
}
else if (*str1 == '\0') {
return -1;
}
else {
return 1;
}
}
int main() {
char string1[100], string2[100];
printf("Enter the first string: ");
fgets(string1, 100, stdin);
printf("Enter the second string: ");
fgets(string2, 100, stdin);
int result = string_compare(string1, string2);
if (result == 0) {
printf("The two strings are equal.\n");
}
else if (result < 0) {
printf("The first string is lexicographically smaller than the second string.\n");
}
else {
printf("The first string is lexicographically greater than the second string.\n");
}
return 0;
}
Output:
Enter the first string: be accountable
Enter the second string: be accountable
The two strings are equal.
Pro-Tips💡
In this program, the string_compare
function takes two pointers as arguments, one for the first string and one for the second string.
function uses the pointers to iterate through the two strings, comparing the characters at each position using the dereference operator *
.
If a mismatch is found, the function returns the difference between the ASCII values of the mismatched characters.
If the two strings are identical up to the point where one of them ends, the function returns -1 if the first string is shorter,
1 if the second string is shorter or 0 if both strings are of the same length and have the same characters.
In the main function, the user is prompted to enter two strings which are read by fgets
and stored in the variables string1
and string2
.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.