C Program to Compare Two Strings Using Pointers
Last Updated :
11 Mar, 2024
In C, strings are arrays of characters terminated by a null character ('\0'
) and pointers can be used to traverse these arrays and compare the characters in two strings. In this article, we will learn how to compare two strings using pointers in C.
For Example,
Input:
char str1[] = "Hello";
char str2[] = "World";
Output:
Hello and World are not Equal
Comparing Two Strings Using Pointers in C
We can compare two strings using pointers by going through each character one by one and comparing whether it is equal or not till we reach the end of either string. The below approach defines how to do it.
Approach
- Create a function that takes two character pointers as arguments that point to each string.
- Iterate through the characters of both strings simultaneously using pointers and check if the current characters of both strings are equal, move to the next characters. If a pair of characters are not equal, return
false
.
- If the end of both strings is reached without finding any unequal characters, return
true
, indicating that the strings are equal.
- Based on the return value of the function, print whether the strings are equal or not.
C Program to Compare Two Strings Using Pointers
The below program demonstrates how we can compare the given strings using pointers in C.
C
#include <stdbool.h>
#include <stdio.h>
bool compare( char * str1, char * str2)
{
while (*str1 == *str2) {
if (*str1 == '\0' && *str2 == '\0' )
return true ;
str1++;
str2++;
}
return false ;
}
int main()
{
char str1[] = "Hello" ;
char str2[] = "World" ;
if (compare(str1, str2) == 1)
printf ( "%s and %s are Equal" , str1, str2);
else
printf ( "%s and %s are not Equal" , str1, str2);
return 0;
}
|
Output
Hello and World are not Equal
Time Complexity: O(N), here N is the length of the strings.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...