In the following Java program, we will check if one String can be obtained by rotating characters of another String.
For example, following Strings can be obtained by rotating letters of word “hello”:
elloh
llohe
lohel
Here is the Java code for the same :
package com.topjavatutorial; public class Demo { public static void main(String[] args) { String str1 = "hello"; String str2 = "elloh"; if (isRotation(str1, str2)) System.out.println(str2 + " is a rotated version of " + str1); else System.out.println(str2 + " is not a rotated version of " + str1); } public static boolean isRotation(String s1, String s2) { return (s1.length() == s2.length()) && ((s1 + s1).indexOf(s2) != -1); } }
Output :
elloh is a rotated version of hello
© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post