Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now