C++ Program to compare two string using pointers
Given two strings, compare the strings using pointers
Examples:
Input: str1 = geeks, str2 = geeks
Output: Both are equal
Input: str1 = hello, str2 = hellu
Output: Both are not equal
As their length are same but characters are different
The idea is to dereference given pointers, compare values and advance both of them.
C++
#include <iostream>
using namespace std;
bool compare( char *str1, char *str2)
{
while (*str1 == *str2)
{
if (*str1 == '\0' && *str2 == '\0' )
return true ;
str1++;
str2++;
}
return false ;
}
int main()
{
char str1[] = "geeks" ;
char str2[] = "geeks" ;
if (compare(str1, str2) == 1)
cout << str1 << " " << str2 << " are Equal" ;
else
cout << str1 << " " << str2 << " are not Equal" ;
}
|
Output
geeks geeks are Equal
Complexity analysis:
- Time Complexity: O(min(M, N)), where M and N represents the length of the given strings.
- Auxiliary Space: O(1), no extra space is required, so it is a constant.
Last Updated :
07 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...