The Wayback Machine - https://web.archive.org/web/20241112113659/https://www.geeksforgeeks.org/program-to-check-if-two-strings-are-same-or-not/
Open In App

Check if two strings are same or not

Last Updated : 17 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Examples:

Input: s1 = “abc”, s2 = “abc” 
Output: Yes 

Input: s1 = “”, s2 = “” 
Output: Yes 

Input: s1 = “GeeksforGeeks”, s2 = “Geeks” 
Output: No 

Using (==) in C++/Python/C#, equals in Java and === in JavaScript

C++
#include <bits/stdc++.h>
using namespace std;

int main()
{
    string s1 = "abc";
    string s2 = "abcd";
  
    if (s1 == s2) {
        cout << "Yes" << endl;
    }
    else {
        cout << "No" << endl;
    }
    return 0;
}
Java
public class StringCompare {
    public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "abcd";

        // Compare the strings
        if (s1.equals(s2)) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}
Python
s1 = "abc"
s2 = "abcd"

# Compare the strings
if s1 == s2:
    print("Yes")
else:
    print("No")
C#
using System;

class Program {
    static void Main() {
        string s1 = "abc";
        string s2 = "abcd";

        // Compare the strings
        if (s1 == s2) {
            Console.WriteLine("Yes");
        } else {
            Console.WriteLine("No");
        }
    }
}
JavaScript
let s1 = "abc";
let s2 = "abcd";

// Compare the strings
if (s1 === s2) {
    console.log("Yes");
} else {
    console.log("No");
}

Output
No

Using String Comparison Functions

C++
#include <iostream>
#include <cstring> 

using namespace std;

int main() {
    char s1[] = "hello";
    char s2[] = "hello";

    if (strcmp(s1, s2) == 0) {
        cout << "Yes" << endl; 
    } else {
        cout << "No" << endl;  
    }

    return 0;
}
C
#include <stdio.h>
#include <string.h>

int main() {
    char s1[] = "hello";
    char s2[] = "hello";
    if (strcmp(s1, s2) == 0) {
        printf("Yes\n");
    } else {
        printf("No\n");
    }

    return 0;
}
Java
public class StringCompare {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "hello";

        // Compare the strings using compareTo
        if (s1.compareTo(s2) == 0) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}
C#
using System;

class Program {
    static void Main() {
        string s1 = "hello";
        string s2 = "hello";

        // Compare the strings using CompareTo
        if (s1.CompareTo(s2) == 0) {
            Console.WriteLine("Yes");
        } else {
            Console.WriteLine("No");
        }
    }
}
JavaScript
let s1 = "hello";
let s2 = "hello";

// Compare the strings using localeCompare
if (s1.localeCompare(s2) === 0) {
    console.log("Yes"); 
} else {
    console.log("No");  
}

Output
Yes

Writing your Own Method

C++
#include <iostream>
using namespace std;

bool areStringsEqual(string &s1, string &s2) {
  
    // Compare lengths first
    if (s1.length() != s2.length()) {
        return false;
    }

    // Compare character by character
    for (size_t i = 0; i < s1.length(); ++i) {
        if (s1[i] != s2[i]) {
            return false; 
        }
    }

    return true; 
}

int main() {
    string s1 = "hello";
    string s2 = "hello";

    if (areStringsEqual(s1, s2)) {
        cout << "Yes" << endl; 
    } else {
        cout << "No" << endl;  
    }

    return 0;
}

Output
Yes




Previous Article
Next Article

Similar Reads

Check if given strings can be made same by swapping two characters of same or different strings
Given an array of equal-length strings, arr[] of size N, the task is to check if all the strings can be made equal by repeatedly swapping any pair of characters of same or different strings from the given array. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = { "acbdd", "abcee" } Output: YES Explanation: Swapp
11 min read
Check whether two strings contain same characters in same order
Given two strings s1 and s2, the task is to find whether the two strings contain the same characters that occur in the same order. For example string "Geeks" and string "Geks" contain the same characters in same order. Examples: Input: s1 = "Geeks", s2 = "Geks" Output: Yes Input: s1 = "Arnab", s2 = "Andrew" Output: No Approach: We have two strings
9 min read
Meta Strings (Check if two strings can become same after a swap in one string)
Given two strings, the task is to check whether these strings are meta strings or not. Meta strings are the strings which can be made equal by exactly one swap in any of the strings. Equal string are not considered here as Meta strings. Examples: Input : str1 = "geeks" str2 = "keegs"Output : YesBy just swapping 'k' and 'g' in any of string, both wi
8 min read
Check if two strings are same or not without using library functions
Given two strings S1 and S2, the task is to check whether they are the same or not without using string library functions. Examples: Input: S1 = ”GeeksForGeeks”, S2 = ”GeeksForGeeks”Output: TrueExplanation:S1 and S2 are the same strings Input: S1 = ”GeeksForGeeks”, S2 = ”GeeksforGeeks”Output: False Approach: Follow the steps below to solve the prob
5 min read
Count of same length Strings that exists lexicographically in between two given Strings
Given two string S1 and S2 of length L, the task is to count the number of strings of length L, that exists in between S1 and S2, which are lexicographically greater than S1 but smaller than S2. Examples: Input: S1 = "b", S2 = "f" Output: 3 Explanation: These are 3 strings which come lexicographically in between S1 and S2 i.e. "c", "d" & "e"Inp
8 min read
Check if a string can be split into two strings with same number of K-frequent characters
Given a string S and an integer K, the task is to check if it is possible to distribute these characters into two strings such that the count of characters having a frequency K in both strings is equal. If it is possible, then print a sequence consisting of 1 and 2, which denotes which character should be placed in which string. Otherwise, print NO
11 min read
Check if a palindromic string can be obtained by concatenating substrings split from same indices of two given strings
Given two strings A and B of length N, the task is to check if any of the two strings formed by splitting both the strings at any index i (0 ≤ i ≤ N - 1) and concatenating A[0, i] and B[i, N - 1] or A[i, N - 1] and B[0, i] respectively, form a palindromic string or not. If found to be true, print "Yes". Otherwise, print "No". Examples: Input: A = "
15+ min read
Minimum sum of two elements from two arrays such that indexes are not same
Given two arrays a[] and b[] of same size. Task is to find minimum sum of two elements such that they belong to different arrays and are not at same index in their arrays. Examples: Input : a[] = {5, 4, 13, 2, 1} b[] = {2, 3, 4, 6, 5}Output : 3We take 1 from a[] and 2 from b[]Sum is 1 + 2 = 3.Input : a[] = {5, 4, 13, 1} b[] = {3, 2, 6, 1}Output : 3
15+ min read
Check if two same sub-sequences exist in a string or not
Given a string, the task is to check if there exist two equal sub-sequences in the given string. Two sub-sequences are said to be equal if they have the same characters arranged in the same lexicographical order but the position of characters differs from that in the original string. Examples: Input: str = "geeksforgeeks" Output: YES Two possible s
5 min read
Check whether two points (x1, y1) and (x2, y2) lie on same side of a given line or not
Given three integers a, b and c which represents coefficients of the equation of a line a * x + b * y - c = 0. Given two integer points (x1, y1) and (x2, y2). The task is to determine whether the points (x1, y1) and (x2, y2) lie on the same side of the given line or not.Examples: Input : a = 1, b = 1, c = 1, x1 = 1, y1 = 1, x2 = 1, y2 = 2 Output :
6 min read
Check if two elements of a matrix are on the same diagonal or not
Given a matrix mat[][], and two integers X and Y, the task is to check if X and Y are on the same diagonal of the given matrix or not. Examples: Input: mat[][]= {{1, 2}. {3, 4}}, X = 1, Y = 4 Output: YesExplanation:Both X and Y lie on the same diagonal. Input: mat[][]= {{1, 2}. {3, 4}}, X = 2, Y = 4Output: No Approach: The key observation to solve
7 min read
Check whether two convex regular polygon have same center or not
Given two positive integers N and M which denotes the sides of the convex regular polygon where N < M, the task is to check whether polygons have the same center or not if N-sided polygon was inscribed in an M-sided polygon.Center of Polygon: Point inside a polygon which is equidistant from each vertex of the polygon. Examples: Input: N = 9, M =
3 min read
Check if the relative ordering of elements in given two Arrays is same or not
Given two arrays A[] and B[] each of size N, the task is to check if the sequencing of both the arrays is the same or not. If the sequencing of both the arrays is same, the print Yes otherwise print No. Examples: Input: A[] = { 10, 12, 9, 11 }, B[] = { 2, 7, -3, 5 };Output: YesExplanation: In both the arrays, the relative ordering of elements are s
7 min read
Check whether two strings can be made equal by reversing substring of equal length from both strings
Give two strings S1 and S2, the task is to check whether string S1 can be made equal to string S2 by reversing substring from both strings of equal length. Note: A substring can be reversed any number of times. Example: Input: S1 = "abbca", S2 = "acabb" Output: Yes Explanation: The string S1 and S2 can be made equal by: Reverse S1 in the range [2,
12 min read
Check if two strings can be made equal by reversing a substring of one of the strings
Given two strings X and Y of length N, the task is to check if both the strings can be made equal by reversing any substring of X exactly once. If it is possible, then print "Yes". Otherwise, print "No". Examples: Input: X = "adcbef", Y = "abcdef"Output: YesExplanation: Strings can be made equal by reversing the substring "dcb" of string X. Input:
12 min read
Check if concatenation of two strings is balanced or not
Given two bracket sequences S1 and S2 consisting of '(' and ')'. The task is to check if the string obtained by concatenating both the sequences is balanced or not. Concatenation can be done by s1+s2 or s2+s1. Examples: Input: s1 = ")()(())))", s2 = "(()(()(" Output: Balanced s2 + s1 = "(()(()()()(())))", which is a balanced parenthesis sequence. I
15 min read
Check whether two strings are equivalent or not according to given condition
Given two strings A and B of equal size. Two strings are equivalent either of the following conditions hold true: 1) They both are equal. Or, 2) If we divide the string A into two contiguous substrings of same size A1 and A2 and string B into two contiguous substrings of same size B1 and B2, then one of the following should be correct: A1 is recurs
12 min read
Check if two strings after processing backspace character are equal or not
Given two strings s1 and s2, let us assume that while typing the strings there were some backspaces encountered which are represented by #. The task is to determine whether the resultant strings after processing the backspace character would be equal or not. Examples: Input: s1= geee#e#ks, s2 = gee##eeks Output: True Explanation: Both the strings a
8 min read
Check if concatenation of splitted substrings of two given strings forms a palindrome or not
Given two strings a and b of the same length, the task is to check if splitting both the strings and concatenating their opposite substrings, i.e. concatenating the left substring of a with right substring of b or concatenating the left substring of b with right substring of a, forms a palindrome or not. If found to be true print "Yes". Otherwise,
8 min read
Check if two strings are k-anagrams or not
Given two strings of lowercase alphabets and a value k, the task is to find if two strings are K-anagrams of each other or not.Two strings are called k-anagrams if following two conditions are true. Both have same number of characters.Two strings can become anagram by changing at most k characters in a string.Examples : Input: str1 = "anagram" , st
15+ min read
Count of sub-strings that do not contain all the characters from the set {'a', 'b', 'c'} at the same time
Given a string str consisting only of the characters 'a', 'b' and 'c', find the number of sub-strings that do not contain all the three characters at the same time.Examples: Input: str = "abc" Output: 5 The possible substrings are "a", "b", "c", "ab" and "bc"Input: str = "babac" Output: 12 Approach: The idea is to use three variables a_index, b_ind
8 min read
Loss when two items are sold at same price and same percentage profit/loss
Given the Selling price i.e 'SP' of the two items each. One item is sold at 'P%' Profit and other at 'P%' Loss. The task is to find out the overall Loss.Examples: Input: SP = 2400, P = 30% Output: Loss = 474.725 Input: SP = 5000, P = 10% Output: Loss = 101.01 Approach: How does the above formula work? For profit making item : With selling price (10
4 min read
Count elements of same value placed at same indices of two given arrays
Given two arrays A[] and B[] of N unique elements, the task is to find the maximum number of matched elements from the two given arrays. Elements of the two arrays are matched if they are of the same value and can be placed at the same index (0-based indexing).(By right shift or left shift of the two arrays). Examples: Input: A[] = { 5, 3, 7, 9, 8
8 min read
Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}Output: 5Explanation:Below are the possible arrangement
14 min read
Check if two non-duplicate strings can be made equal after at most two swaps in one string
Given two strings A and B consisting of unique lowercase letters, the task is to check if both these strings can be made equal by using at most two swaps. Print Yes if they can. Otherwise, print No. Example: Input: A="abcd", B="badc"Output: YesFirst swap a and b, and then swap c and d, in string A.Input: A="abcd", B="cbda"Output: No Approach: In th
15+ min read
Minimum cost to make two strings same
Given four integers a, b, c, d and two strings S1 and S2 of equal length, which consist only of the characters '2', '1' and '0'. Converting '1' to '2' or vice versa costs a.Converting '2' to '3' or vice versa costs b.Converting '3' to '1' or vice versa costs c.Deleting the ith character from both the strings costs d. The task is to find the minimum
7 min read
Minimum number of pairs required to make two strings same
Given two strings s1 and s2 of same length, the task is to count the minimum number of pairs of characters (c1, c2) such that by transforming c1 to c2 or c2 to c1 any number of times in any string make both the strings same. Examples: Input: s1 = "abb", s2 = "dad" Output: 2 Transform 'a' -> 'd', 'b' -> 'a' and 'b' -> 'a' -> 'd' in s1. W
8 min read
Minimize replacements or swapping of same indexed characters required to make two given strings palindromic
Given two strings, str1 and str2 consisting of N lowercase alphabets, the task is to find the minimum count of operations of the following two types to make both the strings palindromic string. Replace any character of the strings to any other character([a - z]).Swap any two characters present at the same index in both the strings. Examples: Input:
8 min read
Count substrings of same length differing by a single character from two given strings
Given two strings S and T of length N and M respectively, the task is to count the number of ways of obtaining same-length substring from both the strings such that they have a single different character. Examples: Input: S = "ab", T = "bb"Output: 3Explanation: The following are the pairs of substrings from S and T differ by a single character: ("a
7 min read
Transform the given String into two same Strings by removing at most one character
Given a string S of length N where (N ? 1). The task is to check whether by removing at most one character from the given string it can be divided into two same sub-strings or not return YES or NO for possibilities. Examples: Input: N = 5, S = abzabOutput: YESExplanation: Character 'z' at index 3 can be removed so that the remaining S will be "abab
9 min read
Practice Tags :
three90RightbarBannerImg