How to reverse only the alphabetic characters in a string, keeping other characters in place with Scala

1 Answer

0 votes
object Main {
  def reverseOnlyAlphabeticCharacters(s: String): String = {
    val chars = s.toCharArray
    var i = 0
    var j = chars.length - 1

    while (i < j) {
      if (!chars(i).isLetter) {
        i += 1
      } else if (!chars(j).isLetter) {
        j -= 1
      } else {
        val tmp = chars(i)
        chars(i) = chars(j)
        chars(j) = tmp
        i += 1
        j -= 1
      }
    }

    new String(chars)
  }

  def main(args: Array[String]): Unit = {
    val s = "a1-bC2-dEf3-ghIj"

    println(s)
    println(reverseOnlyAlphabeticCharacters(s))
  }
}




/*
run:

a1-bC2-dEf3-ghIj
j1-Ih2-gfE3-dCba

*/

 



answered Mar 6 by avibootz
edited Mar 6 by avibootz

Related questions

...