String Rotation in Java
Check if one string is rotation of another.
IntermediateModule 4: String ProgramsExample 9 of 25
string-rotation.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Enter first string: ");7 String s1 = sc.nextLine();8 System.out.print("Enter second string: ");9 String s2 = sc.nextLine();1011 if (s1.length() == s2.length() && (s1 + s1).contains(s2)) {12 System.out.println("Rotation");13 } else {14 System.out.println("Not Rotation");15 }16 sc.close();17 }18}
Output
Enter first string: abcde Enter second string: cdeab Rotation
What's going on
We double the first string and check if the second is a substring.