w3resource

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?



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-16.php