In this post, I am going to solve the problem of comparing two strings using pointers In C++.
Examples:
Input: str1 = qwerty, str2 = qwerty
Output: Both are equal
Input: str1 = qwerty, str2 = keypad
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.
Join Our Community
Join our WhatsApp Group To know more about Programming Language tips, tricks and knowledge about and how to start learning any programming language.
Program Comparing Two Strings Using Pointers In C++
// C++ Program to compare two strings using // Pointers #include <iostream> using namespace std; // Method to compare two string // using pointer bool compare(char *str1, char *str2) { while (*str1 == *str2) { if (*str1 == '\0' && *str2 == '\0') return true; str1++; str2++; } return false; } int main() { // Declare and Initialize two strings char str1[] = "qwerty"; char str2[] = "qwerty"; if (compare(str1, str2) == 1) cout << str1 << " " << str2 << " are Equal"; else cout << str1 << " " << str2 << " are not Equal"; }
Output:
qwerty qwerty are equal.