Introduction To Scala — Part5 — Strings

/**
 * Exercise 5.1.
 * Write a function string_reverse : string -> unit to reverse a
 * string in-place.
 *
 */
def string_reverse(s: String): String = {
  val len = s.length / 2 - 1
  val sb = new StringBuilder(s)
  for (i < - 0 to len) {
    val c = sb(i)
    sb(i) = sb(s.length -i - 1)
    sb(s.length - i - 1) = c
  }
  sb.toString
}
 
 
// Test
val stringTest1 = "Aleksandr Dugin"
val stringTest2 = "Olavo de Carvalho"
val rev1 = string_reverse(stringTest1)
val rev2 = string_reverse(stringTest2)
println("Original: " + stringTest1 + "    reversed: " + rev1)
println("Original: " + stringTest2 + "    reversed: " + rev2)