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?
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework