In this post, we will see how to check if one String is rotation of another or not.
For example:
1 2 3 4 5 |
java2blog and blogjava2 are rotation of each other. java2blog and avablog2j are not rotation of each other. |
Approach:
Lets say you need to check whether str1
and str2
is 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 rotation of another.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package org.arpit.java2blog; public class StringRotationMain { public static void main(String[] args) { System.out.println( "java2blog and blogjava2 are rotation of each other : " + isRotation("java2blog", "blogjava2")); System.out.println( "java2blog and avablog2j are rotation of each other : " + isRotation("java2blog", "avablog2j")); } public static boolean isRotation(String str, String rotation) { String str2 = str + str; if (str2.contains(rotation)) { return true; } return false; } } |
When you run above program, you will get below output:
java2blog and avablog2j are rotation of each other : false
That’s all about how to check if one String is rotation of another String in java