Q:

Write a Scala program to reverse every word in a given string

0

Write a Scala program to reverse every word in a given string.

All Answers

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

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

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