Friday, 17 August 2018

C++ Program to Generate all the Rotations of a String

We will discuss an easy approach to generate all the rotations of a string. Approach is simple we will concatenate the given string with itself and then we will be able to generate all the rotations. C++ Program to generate all the rotations of a given string is given below along with its algorithm.

Algorithm: 

step 1: Let string s="plex" 
step 2: Let string temp=s  i.e (temp="plex")
step 3: Set temp=temp+temp i.e (temp="plexplex")
step 4: set i=0,j=0
step 5: For i=0 to length(s):
                  declare an empty variable e.g temp1=""
                  For j=0 to length(s):
                            set temp1=temp1+temp[i+j]
                  print(temp1)
                            

Program:

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

int main(){

	  string s;
	  cout<<"\nEnter the string to find out its rotations: \n";
	  cin>>s;

      //a string container to store all the rotations
      std::vector<string> vect; 

      //copying string s into temp
      string temp=s;


	  //now contacenate string 'temp' with itself..
	  //ex: temp="plexinfo" so, after concatenation temp="plexinfoplexinfo"
      temp=temp+temp;
      // cout<<temp<<"\n";

      //loop from 0 to length(s)-
      for(int i=0;i<s.size();i++){

      	   string temp1=""; //declaring an empty string

      	   for(int j=0;j<s.size();j++){
      	   	     temp1=temp1+temp[i+j];  
      	   }
      	   vect.push_back(temp1);
      }

      cout<<"\nAll the rotations of the given string are:\n\n";
      for(int i=0;i<vect.size();i++){
      	    cout<<vect[i]<<"\n";
      }
      return 0;

}


OUTPUT:


 


EmoticonEmoticon