Check String Rotation

This program checks if one string is rotation of another.

Problem Statement

Write a Java program to check if "waterbottle" is rotation of "erbottlewat".

Source Code

1 public class StringRotationCheck {
2 public static void main(String[] args) {
3 System.out.println("Eduinq String Rotation Check");
4 String s1="waterbottle", s2="erbottlewat";
5 if(s1.length()==s2.length() && (s1+s1).contains(s2))
6 System.out.println("String is rotation");
7 else System.out.println("String is not rotation");
8 }
9 }

Program Output

Eduinq String Rotation Check
String is rotation

Explanation

The first string is concatenated with itself, and if the second string is a substring of this doubled string and both have equal lengths, the second is guaranteed to be a rotation of the first, demonstrating an elegant rotation check.

Quick Links to Explore