1. Introduction
Strings are a fundamental concept in programming, and often, there's a need to compare them. While there are built-in functions to do this, understanding the process at a lower level using pointers offers valuable insight. In this tutorial, we will look at how to compare two strings manually using pointers.
2. Program Overview
1. Declare two character arrays (strings).
2. Declare two character pointers.
3. Use the pointers to traverse and compare the strings character by character.
4. Return the comparison result.
3. Code Program
#include <stdio.h>
// Function to compare two strings using pointers
int compareStrings(char *str1, char *str2) {
while (*str1 && (*str1 == *str2)) {
str1++;
str2++;
}
return *(unsigned char *)str1 - *(unsigned char *)str2;
}
int main() {
char string1[100], string2[100];
// Input the strings
printf("Enter the first string:\n");
gets(string1);
printf("Enter the second string:\n");
gets(string2);
// Compare the strings
int result = compareStrings(string1, string2);
// Display the comparison result
if(result == 0) {
printf("Both strings are identical.\n");
} else if(result > 0) {
printf("The first string is greater than the second.\n");
} else {
printf("The second string is greater than the first.\n");
}
return 0;
}
Output:
Enter the first string: Hello Enter the second string: Hello Both strings are identical.
4. Step By Step Explanation
1. We begin with the declaration of two character arrays, string1, and string2, to store our input strings.
2. The compareStrings function is designed to compare two strings. This function uses two pointers (str1 and str2) to iterate through the characters of each string. The while loop inside this function will continue as long as characters from both strings are equal and not the null terminator.
- If a difference is found or one of the strings terminates before the other, the loop will stop, and the function will return the difference of the ASCII values of the characters where the mismatch is first found.
3. In the main function, the user is prompted to input two strings. We use the gets function to read them (note that gets can be risky due to potential buffer overflows; it's used here for simplicity).
4. The compareStrings function is called to compare the two strings.
5. Depending on the returned result:
- If it's 0, the strings are identical.
- If it's positive, the first string is lexicographically greater.
- If it's negative, the second string is lexicographically greater.
6. The comparison result is then displayed to the user.
Comments
Post a Comment
Leave Comment