w3resource

Scala Programming: Create a new string from a given string swapping the last two characters of the given string

Scala Programming String Exercise-20 with Solution

Write a Scala program to create a new string from a given string swapping the last two characters of the given string. The length of the given string must be two or more.

Sample Solution:

Scala Code:

object Scala_String {
  def lastTwo(str1: String): String = {
    if (str1.length() < 2) return str1;
    return str1.substring(0, str1.length - 2) + str1.charAt(str1.length - 1) + str1
      .charAt(str1.length - 2);
  }
  def main(args: Array[String]): Unit = {
    var str1 ="String";
    println("The given strings is: " + str1);
    println("The string after swap last two characters are: " + lastTwo(str1));
    str1 ="Scala";
    println("The given strings is: " + str1);
    println("The string after swap last two characters are: " + lastTwo(str1));
  }
}

Sample Output:

The given strings is: String
The string after swap last two characters are: Strign
The given strings is: Scala
The string after swap last two characters are: Scaal

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to append two given strings such that, if the concatenation creates double characters then omit one of the characters.
Next: Write a Scala program to read a string and return true if it ends with a specified string of length 2.

What is the difficulty level of this exercise?