Skip to content
Related Articles

Related Articles

Improve Article
C++ Program to compare two string using pointers
  • Last Updated : 04 Nov, 2018

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.

Program:




// 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[] = "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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes 

My Personal Notes arrow_drop_up
Recommended Articles
Page :