Check if strings are rotations of each other or not in C++

Hello, guys in this tutorial we will learn how to check if strings are rotation of each other or not in C++.

Example 1
input
string1="codespeedy"
string2="speedycode"
Output
true
Example 2
input
string1="ABCD"
string3="ACBD"
Output
false

Algorithm-

  1. If string lengths are not the same return false.
  2. Create a temporary string tempstr.
  3. Concate string1 with string1.
  4. Then check if string2 is a substring of tempstr.

If tempstr and string2 substring of each other then string1 and string2  rotated form of each other.

#include <iostream>
#include<string>
using namespace std;

bool funcheck(string string1,string string2)
{
  if(string1.length()!=string2.length())   //if length of strings are not equal return false
  return false;
  
 
  
   string temp=string1+string1;         //concating string1 with string1 
  
  if(temp.find(string2)!=string::npos)       // checking if string2 is substring of temp string
  return true;
  
  return false;
    
}


int main() {
  
 string string1,string2;       //declaring string variable
 
 cout <<"ENTER FIRST STRING"<<endl; 
 
 cin>>string1;                      //taking string as input
 
 cout<<"ENTER SECOND STRING"<<endl;  
 
 cin>>string2;                    //taking string as input
 
 if(funcheck(string1,string2))               //if string is rotated
 cout <<"STRINGS ARE ROTATED"<<endl;        //print this statement
 else                                       //else
 cout <<"STRINGS ARE NOT ROTATED"<<endl;     //print this statement
 
 
 return 0;   
}
  
  
  
  
  
 
input 
string1="codespeedy" 
string2="speedycode" 
Output 
true 
Example 2 
input 
string1="ABCD" 
string3="ACBD"
Output
false

Also read: Finding the Number of Vowels, Consonants, Digits, and White Spaces in a String in C++

Leave a Reply

Your email address will not be published. Required fields are marked *