A Program to check if strings are rotations of each other or not

A String is said to be a rotation of another String, if it has the same length, contains same characters, and they were rotated around one of the characters.

For example, String bcda is a rotation of abcd but bdca is not a rotation of String abcd.

One of the simplest solutions to this interesting problem is first to check if two String has the same length, if not then one String cannot be the rotation of another.

If they are of the same length then just create another String by concatenating first String with itself, now check if second String is a substring of this concatenated String or not, if yes, then second String is a rotation of first.

Kotlin program to check if strings are rotations of each other or not

/* Function checks if passed strings (str1 and str2)
       are rotations of each other */
fun areRotations(str1:String, str2:String):Boolean
    // There lengths must be same and str2 must be
    // a substring of str1 concatenated with str1.
    return (str1.length == str2.length) &&
            ((str1 + str1).indexOf(str2) != -1);

fun main(args: Array<String>) {
    var str1 = "AACD";
    var str2 = "ACDA";

    if (areRotations(str1, str2))
        System.out.println("Strings are rotations of each other");
        System.out.printf("Strings are not rotations of each other");


Strings are rotations of each other

Join My Facebook Group
Join Group
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions