1. Introduction
In Java, we can check if one string is a rotated version of another by comparing the lengths of the two strings and checking whether one string is a substring of another string concatenated with itself. In this tutorial, we will learn how to check whether one string is a rotated version of another string in Java.
2. Program Steps
1. Define a main method to serve as the entry point of the program.
2. Define two strings: one that needs to be checked as a rotated version of the other.
3. Check if the length of the two strings is the same, and the concatenated original string contains the string to be checked as a substring.
4. Print the result.
3. Code Program
public class CheckRotatedString {
public static void main(String[] args) {
// Step 2: Define two strings
String str1 = "ABCD";
String str2 = "CDAB";
// Step 3: Check if str2 is a rotated version of str1
if (str1.length() == str2.length() && (str1 + str1).contains(str2)) {
// Step 4: Print the result
System.out.println(str2 + " is a rotated version of " + str1);
} else {
System.out.println(str2 + " is not a rotated version of " + str1);
}
}
}
Output:
CDAB is a rotated version of ABCD
4. Step By Step Explanation
– Step 1: The main method is defined, acting as the entry point of the program.
– Step 2: Two strings str1 and str2 are defined. We want to check if str2 is a rotated version of str1.
– Step 3: We compare the lengths of str1 and str2. Then we concatenate str1 with itself and check if it contains str2 as a substring.
– Step 4: Based on the result of the check in Step 3, we print whether str2 is a rotated version of str1 or not.
Thus, the program correctly identifies whether one string is a rotated version of another string and prints the result.