Q:

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

0

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

All Answers

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

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

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