Array-promo

Question

Determine whether a given string is rotation to another string.

To find rotation of string , we concatenate string 1 with string 1. Then, try to find the string 2  in concatenated string using indexOf() method. If string 2 is present in concatenated string then, string 2 is rotation of string 1. 

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					
import java.util.Scanner;
public class rotationString 
{  
    public static void main(String[] args)
    {  
        String str="",str1="";
        int i=0,len=0;
        Scanner sc = new Scanner(System.in);    
        
        System.out.println("Enter 1st string");   
        str = sc.next();
        System.out.println("Enter 2nd string");   
        str1 = sc.next();
        
        if(str.length() != str1.length())
        {  
            System.out.println(str1+" is not a rotation of "+str);  
        }  
        else
        {  
            /*Concatenate str with str and store it in str*/  
            str = str+str;  
              
            /*Check whether str1 is present in str*/  
            if(str.indexOf(str1) != -1)  
                System.out.println(str1+" is  a rotation of "+str);  
            else  
                System.out.println(str1+" is not a rotation of "+str);  
        }  
    }  
}    

				
			

Coding Store

Leave a Reply

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