The Wayback Machine - https://web.archive.org/web/20230312022629/https://www.geeksforgeeks.org/program-to-check-if-two-strings-are-same-or-not/
Skip to content
Related Articles
Open in App
Not now

Related Articles

Program to check if two strings are same or not

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 07 Mar, 2023
Improve Article
Save Article

Given two strings, the task is to check if these two strings are identical(same) or not. 

Examples:

Input: string1 = “GeeksforGeeks”, string2 = “GeeksforGeeks” 
Output: Yes 

Input: string1 = “Geeks for Geeks”, string2 = “Geeks for Geeks” 
Output: Yes 

Input: string1 = “GeeksforGeeks”, string2 = “Geeks” 
Output: No 

Input: string1 = “Geeks for Geeks”, string2 = “Geeks for geeks” 
Output: No

Brute Force Way:

     The Approach:

           Using (==) Operator in C++/Java and using (is) operator in Python.

C++




#include <iostream>
#include<string>
#include<bits/stdc++.h>
using namespace std;
 
int main() {
    // first string.
    string s1 = "GeeksforGeeks";
    // second string.
    string s2 = "Geeks for geeks";
    // check condition.
    if(s1==s2){
      cout<<"Strings Are Equal"<<endl;
    }else{
      cout<<"Strings Are Not Equal"<<endl;
    }
    return 0;
}

Java




import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        // first string
        String s1 = "GeeksforGeeks";
        // second string
        String s2 = "Geeks for geeks";
        // check condition
        if (s1.equals(s2)) {
            System.out.println("Strings Are Equal");
        } else {
            System.out.println("Strings Are Not Equal");
        }
    }
}
// This code is contributed by divyansh2212

Python3




# Python3 program to check 2 strings are identical or not
 
if __name__ == "__main__":
   
  #first string.
  string1 = "GeeksforGeeks"
  #second string.
  string2 = "Geeks for geeks"
 
  #check condition
  if (string1 is string2):
    print("Strings Are Equal")
  else:
    print("Strings Are Not Equal")
 
   
  # This Code is contributed by Pratik Gupta

C#




using System;
 
class GFG
{
    static void Main(string[] args)
    {
        // first string
        string s1 = "GeeksforGeeks";
        // second string
        string s2 = "Geeks for geeks";
        // check condition
        if (s1 == s2)
        {
            Console.WriteLine("Strings Are Equal");
        }
        else
        {
            Console.WriteLine("Strings Are Not Equal");
        }
    }
}
// code by ksam24000

Javascript




// js code implementation
 
const s1 = "GeeksforGeeks";
const s2 = "Geeks for geeks";
 
if (s1 === s2) {
    console.log("Strings Are Equal");
} else {
    console.log("Strings Are Not Equal");
}
// code by ksam24000

Output

Strings Are Not Equal

Complexity Analysis:

Time Complexity: O(1).
Auxiliary Space: O(1).

Approach 1: 

This can be done with the help of strcmp() method in C. Please note, this method is case-sensitive. 

Implementation: 

C++




// C++ program to check if
// two strings are identical
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    char string1[100], string2[100];
 
    // Get the strings which
    // is to be checked
    cin >> string1;
    cout << "Enter the first string: " << string1;
 
    // Get the strings which
    // is to be checked
    cin >> string2;
    cout << "\nEnter the second string: " << string2;
 
    // Check if both strings are equal
    cout << "\nAre both strings same: ";
 
    if (strcmp(string1, string2) == 0) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
 
    return 0;
}
 
// This code is contributed by Akanksha Rai

C




// C program to check if
// two strings are identical
 
#include <stdio.h>
#include <string.h>
 
int main()
{
 
    char string1[100], string2[100];
 
    // Get the strings which
    // is to be checked
    scanf("%[^\n]\ns", string1);
    printf("Enter the first string: %s", string1);
 
    // Get the strings which
    // is to be checked
    scanf("%[^\n]\ns", string2);
    printf("\nEnter the second string: %s", string2);
 
    // Check if both strings are equal
    printf("\nAre both strings same: ");
 
    if (strcmp(string1, string2) == 0) {
        printf("Yes");
    }
    else {
        printf("No");
    }
 
    return 0;
}

Java




// Java program to check if
// two strings are identical
import java.util.*;
 
class GFG {
 
    // Driver code
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
 
        // Get the strings which is to be checked
        String string1 = in.nextLine();
        System.out.println("Enter the first string: "
                           + string1);
 
        // Get the strings which is to be checked
        String string2 = in.nextLine();
        System.out.println("Enter the second string :"
                           + string2);
 
        // Check if both strings are equal
        System.out.println("\nAre both strings same: ");
 
        if (string1.equals(string2) == true) {
            System.out.println("Yes");
        }
        else {
            System.out.println("No");
        }
    }
}
 
// This code is contributed by aishwarya.27

Python 3




# Python program to check if
# two strings are identical
 
if __name__ == "__main__":
 
    # Get the strings which
    # is to be checked
    string1 = input("Enter the first string: ")
    print(string1, end="\n")
 
    # Get the strings which
    # is to be checked
    string2 = input("Enter the second string: ")
    print(string2, end="\n")
 
    # Check if both strings are equal
    print("Are both strings same: ", end=" ")
 
    if (string1 == string2):
        print("Yes")
 
    else:
        print("No")
 
# This code is contributed by Ryuga

C#




// C# program to check if
// two strings are identical
using System;
 
class GFG {
 
    // Driver code
    public static void Main()
    {
 
        // Get the strings which is to be checked
        String string1 = Console.ReadLine();
        Console.WriteLine("Enter the first string: "
                          + string1);
 
        // Get the strings which is to be checked
        String string2 = Console.ReadLine();
        Console.WriteLine("Enter the second string :"
                          + string2);
 
        // Check if both strings are equal
        Console.WriteLine("\nAre both strings same: ");
 
        if (string1.Equals(string2) == true) {
            Console.WriteLine("Yes");
        }
        else {
            Console.WriteLine("No");
        }
    }
}
 
/* This code contributed by PrinciRaj1992 */

PHP




<?php
// PHP program to check if
// two strings are identical
 
 
// Get the strings which
// is to be checked
$string1 = readline();
echo "Enter the first string: $string1";
 
// Get the strings which
// is to be checked
$string2 = readline();
echo "\nEnter the second string: $string2";
 
// Check if both strings are equal
echo "\nAre both strings same: ";
 
if (strcmp($string1, $string2) == 0)
{
    echo "Yes";
}
 
else if (strcmp($string1, $string2) > 0) //Because string1 has some character greater than string2
{
    echo "No";
}
 
else if (strcmp($string1, $string2) < 0) //Because string2 has some character greater than string1
{
    echo "No";
}
 
// This code is contributed by Ashutosh Tiwari
 
?>

Output

Enter the first string: ��}��
Enter the second string: �`
Are both strings same: No

Time Complexity: O(min(a,b)) // a is the length of the first string and b is the length of the second string.
Auxiliary Space: O(100) 

Approach 2 : (Using two pointer approach)

The problem can be easily solved using two pointer approach. But before using two pointer one basic check that can be performed is the length. As it is very obvious to be same they will contain same length. If both of their length is same then we can perform the 2 pointer technique.

C++




// C++ program to check if
// two strings are identical
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    char string1[100], string2[100];
 
    // Get the strings which
    // is to be checked
    cin >> string1;
    cout << "Enter the first string: " << string1;
 
    // Get the strings which
    // is to be checked
    cin >> string2;
    cout << "\nEnter the second string: " << string2;
 
    // Check if both strings are equal
    cout << "\nAre both strings same: ";
 
    // if their length is not equal then
    // can easily say not equal
    if (strlen(string1) != strlen(string2)) {
        cout << "No";
    }
 
    else {
        // initialize two pointers
        // to traverse on both strings
        int i = 0, j = 0;
 
        // find out the length
        int len1 = strlen(string1), len2 = len1;
 
        // keep a flag
        bool equal = true;
 
        // start traversing
        while (i < len1) {
            // if any of the character is not same
            // can say not equal and make change the flag
            if (string1[i] != string2[j]) {
                equal = false;
                cout << "No";
                break;
            }
 
            // else keep increasing both the pointer
            i++;
            j++;
        }
 
        // now if the flag is not changed
        // i.e. all characters are equal
        // so print yes
        if (equal)
            cout << "Yes";
    }
 
    return 0;
}
 
// This code is contributed by rajdeep999

Java




// Java program to check if
// two strings are identical
import java.util.*;
 
public class GFG {
 
  // Driver code
  public static void main(String[] args)
  {
    Scanner in = new Scanner(System.in);
 
    // Get the strings which is to be checked
    String string1 = in.nextLine();
    System.out.println("Enter the first string: "
                       + string1);
 
    // Get the strings which is to be checked
    String string2 = in.nextLine();
    System.out.println("Enter the second string : "
                       + string2);
 
    // Check if both strings are equal
    System.out.println("\nAre both strings same: ");
 
    if (string1.length() != string2.length()) {
      System.out.println("No");
    }
    else {
      // initialize two pointers
      // to traverse on both strings
      int i = 0, j = 0;
 
      // find out the length
      int len1 = string1.length();
 
      // keep a flag
      boolean equal = true;
 
      // start traversing
      while (i < len1) {
        // if any of the character is not same
        // can say not equal and make change the
        // flag
        if (string1.charAt(i)
            != string2.charAt(j)) {
          equal = false;
          System.out.println("No");
          break;
        }
 
        // else keep increasing both the pointer
        i++;
        j++;
      }
 
      // now if the flag is not changed
      // i.e. all characters are equal
      // so print yes
      if (equal == true) {
        System.out.println("Yes");
      }
    }
  }
}
 
// This code is contributed by Samim Hossain Mondal.

C#




// C# program
using System;
 
class GFG {
 
    // Driver code
    public static void Main()
    {
 
        // Get the strings which is to be checked
        String string1 = Console.ReadLine();
        Console.WriteLine("Enter the first string: "
                          + string1);
 
        // Get the strings which is to be checked
        String string2 = Console.ReadLine();
        Console.WriteLine("Enter the second string :"
                          + string2);
 
        // Check if both strings are equal
        Console.WriteLine("\nAre both strings same: ");
 
        // if their length is not equal then
        // can easily say not equal
        if (string1.Length != string2.Length) {
            Console.WriteLine("No");
        }
 
        else {
            // initialize two pointers
            // to traverse on both strings
            int i = 0, j = 0;
 
            // find out the length
            int len1 = string1.Length;
 
            // keep a flag
            bool equal = true;
 
            // start traversing
            while (i < len1) {
                // if any of the character is not same
                // can say not equal and make change the
                // flag
                if (string1[i] != string2[j]) {
                    equal = false;
                    Console.WriteLine("No");
                    break;
                }
 
                // else keep increasing both the pointer
                i++;
                j++;
            }
 
            // now if the flag is not changed
            // i.e. all characters are equal
            // so print yes
            if (equal == true) {
                Console.WriteLine("Yes");
            }
        }
    }
}
 
// This code is contributed by Samim Hossain Mondal.

Python




# Python program to check if
# two strings are identical
if __name__ == "__main__":
 
    # Get the strings which
    # is to be checked
    string1 = input("Enter the first string: ")
    print(string1, end="\n")
 
    # Get the strings which
    # is to be checked
    string2 = input("Enter the second string: ")
    print(string2, end="\n")
 
    # Check if both strings are equal
    print("Are both strings same: ", end=" ")
 
    # if their length is not equal then
    # can easily say not equal
    if (len(string1) != len(string2)):
        print("No")
 
    else:
        # initialize two pointers
        # to traverse on both strings
        i = 0
        j = 0
 
        # find out the length
        len1 = len(string1)
        len2 = len1
 
        # keep a flag
        equal = True
 
        # start traversing
        while (i < len1):
 
            # if any of the character is not same
            # can say not equal and make change the flag
            if (string1[i] != string2[j]):
                equal = False
                print("No")
                break
 
            # else keep increasing both the pointer
            i += 1
            j += 1
 
        # now if the flag is not changed
        # i.e. all characters are equal
        # so print yes
        if (equal == True):
            print("Yes")
 
# This code is contributed by Samim Hossain Mondal.

Output

Enter the first string: 
Enter the second string: 
Are both strings same: Yes

Time Complexity: O(N), for traversing using two pointers over the string in case their size is equal
Auxiliary Space: O(1), no extra space is used

Approach-3 : Using not equal to(!=) operator

Using the not equal to operator we can check whether both of the strings are equal or not.

C++




#include <iostream>
#include<string>
using namespace std;
 
int main() {
    // first string.
    string s1 = "GeeksforGeeks";
    // second string.
    string s2 = "Geeks for geeks";
    // check condition.
    if(s1!=s2){
      cout<<"Strings Are Not Equal"<<endl;
    }else{
      cout<<"Strings Are Equal"<<endl;
    }
    return 0;
}

Output

Strings Are Not Equal

Complexity Analysis:

Time Complexity: O(1)
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!