string-rotation-kotlin
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");
    else
        System.out.printf("Strings are not rotations of each other");
}


Output


Strings are rotations of each other

 
Join My Facebook Group
Join Group
 

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions