A small code snippet to auto increment alphabets in Scala

Thu, Oct 24, 2013

Programming Scala #programming #scala

Today I came across a function to auto increment alphabets function. The function will take a String and increase the last alphabet. Here are the rules

-“A” becomes “B”

-“Z” becomes “AA”

-“ABZ” becomes “ACA”

-“ZZZ” becomes “AAAA”

I originally wrote this in Java, but I think it will be kinda cool to write it in Scala using recursion. So here you go.

object IncrementAlphabet extends App {
  def increment(str: String): String = {
    def internalIncrement(str: String, index: Integer): String = {
      val chars = str.toCharArray()
      val char = chars(index)
      val charInt = char.toInt
      if (char == 'Z') {
        chars.update(index, 'A')
        if (index == 0) {
          'A' + new String(chars)
        } else {
          internalIncrement(new String(chars), index - 1)
        }

      } else {
        val nextInt = charInt + 1
        chars.update(index, nextInt.toChar)
        new String(chars)
      }
    }
    internalIncrement(str, str.length() - 1)
  }

  println(increment("A"))
  //output: B
  println(increment("F"))
  //output: G
  println(increment("Z"))
  //output: AA
  println(increment("ABZ"))
  //output: ACA
  println(increment("ZZZ"))
  //output: AAAA
  println(increment("AAAAAAZZZZZZZZ"))
  //output: AAAAABAAAAAAAA
}