w3resource

Scala Programming: Check if two given strings are rotations of each other

Scala Programming String Exercise-18 with Solution

Write a Scala program to check if two given strings are rotations of each other.

Sample Solution:

Scala Code:

object Scala_String {

  def checkForRotation(str1: String, str2: String): Boolean = {
    return (str1.length == str2.length) && ((str1 + str1).indexOf(str2) != -1);
  }

  def main(args: Array[String]): Unit = {
    val str1 = "ABACD";
    val str2 = "CDABA";
    println("The given strings are: " + str1 + "  and  " + str2);
    println("\nThe concatination of 1st string twice is: " + str1 + str1
    );

    if (checkForRotation(str1, str2)) {
      println("The 2nd string " + str2 + "  exists in the new string."
      );
      println("\nStrings are rotations of each other");
    } 
    else {
      println("The 2nd string " + str2 + "  not exists in the new string.");
      printf("\nStrings are not rotations of each other");
    }
  }
}

Sample Output:

The given strings are: ABACD  and  CDABA
The concatination of 1st string twice is: ABACDABACD
The 2nd string CDABA  exists in the new string.
Strings are rotations of each other

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to count and print all the duplicates in the input string.
Next: Write a Scala program to append two given strings such that, if the concatenation creates double characters then omit one of the characters.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/scala-exercises/string/scala-string-exercise-18.php