Solution: Let’s say you want 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 the rotation of str1 else it is not
Let's say you need to check whether
str1
andstr2
is the rotation of one another or not.
- Create a new String with
str3
=str1
+str1
- Check if
str3
containsstr2
or not. - if
str3
containsstr2
thenstr2
is rotation ofstr1
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
- Don't miss the next article!
- Be the first to be notified when a new article or Kubernetes experiment is published.