Software Engineering

How to Reverse Letters in Kotlin

The challenge

Given a string str, reverse it omitting all non-alphabetic characters.


For str = "krishan", the output should be "nahsirk".

For str = "ultr53o?n", the output should be "nortlu".


A string consists of lowercase Latin letters, digits, and symbols.

The solution in Kotlin

Option 1:

fun reverseLetter(str: String): String {
    return str.filter(Char::isLetter).reversed()

Option 2:

fun reverseLetter(str: String) = str.reversed().filter{ it.isLetter() }

Option 3:

fun reverseLetter(str: String): String = str.replace(Regex("[^a-zA-Z]"), "").reversed()

Test cases to validate our solution

import kotlin.test.assertEquals
import org.junit.Test

class TestReverseLetter {
  fun `Basic Tests` () {
    val str = "krishan"
    assertEquals("nahsirk", reverseLetter("krishan"))
    assertEquals("nortlu", reverseLetter("ultr53o?n"))
    assertEquals("cba", reverseLetter("ab23c"))
    assertEquals("nahsirk", reverseLetter("krish21an"))