Monday, May 2, 2022

Question 4 : How to check if one String is rotation of another String in java?

 Solution: Let’s say you want to check whether str1 and str2 is the rotation of one another or not.

  1. Create a new String with str3= str1 + str1
  2. Check if str3 contains str2 or not.
  3. if str3 contains str2 then str2 is the rotation of str1 else it is not
  4. Let's say you need to check whether str1 and str2 is the rotation of one another or not.

  • Create a new String with str3= str1 + str1
  • Check if str3 contains str2 or not.
  • if str3 contains str2 then str2 is rotation of str1 else it is not

  • Java Program to check if one String is the rotation of another.
package org.cloudTechtwitter; public class StringRotationMain { public static void main(String[] args) { System.out.println( "CloudTechtwitter and TechtwitterCloud are rotation of each other : " + isRotation("CloudTechtwitter", "TechtwitterCloud")); System.out.println( "CloudTechtwitter and TechCloudtwitter are rotation of each other : " + isRotation("CloudTechtwitter", "TechCloudtwitter")); } public static boolean isRotation(String str, String rotation) { String str2 = str + str; if (str2.contains(rotation)) { return true; } return false; } }

Run code using online java compiler When you run the above program, you will get the below output: CloudTechtwitter and TechtwitterCloud are rotation of each other: true CloudTechtwitter and TechCloudtwitte are rotation of each other: false
  1. Don't miss the next article!
  2. Be the first to be notified when a new article or Kubernetes experiment is published.                            

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS