Scala Programming: Reverse every word of a given string
Scala Programming String Exercise-16 with Solution
Write a Scala program to reverse every word in a given string.
Sample Solution:
Scala Code:
object Scala_String {
def WordsInReverse(str1: String): String = {
val each_words = str1.split(" ");
var revString = "";
for (i <- 0 to each_words.length - 1) {
val word = each_words(i);
var reverseWord = "";
for (j <- word.length - 1 to 0 by -1) {
reverseWord = reverseWord + word.charAt(j);
}
revString = revString + reverseWord + " ";
}
revString;
}
def main(args: Array[String]): Unit = {
val str1 ="This is a test string";
println("The given string is: " + str1);
println("The new string after reversed the words: " + WordsInReverse(str1));
val str2 ="The Scala Programming Language";
println("The given string is: " + str2);
println("The new string after reversed the words: " + WordsInReverse(str2));
}
}
Sample Output:
The given string is: This is a test string The new string after reversed the words: sihT si a tset gnirts The given string is: The Scala Programming Language The new string after reversed the words: ehT alacS gnimmargorP egaugnaL
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Scala program to find the maximum occurring character in a string.
Next: Write a Scala program to count and print all the duplicates in the input string.
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