HomeSoftware EngineeringThe right way to Reverse Letters in Kotlin

The right way to Reverse Letters in Kotlin

The problem

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


For str = "krishan", the output ought to be "nahsirk".

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


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

The answer in Kotlin

Possibility 1:

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

Possibility 2:

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

Possibility 3:

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

Check instances to validate our resolution

import kotlin.check.assertEquals
import org.junit.Check

class TestReverseLetter {
  enjoyable `Fundamental Assessments` () {
    val str = "krishan"
    assertEquals("nahsirk", reverseLetter("krishan"))
    assertEquals("nortlu", reverseLetter("ultr53o?n"))
    assertEquals("cba", reverseLetter("ab23c"))
    assertEquals("nahsirk", reverseLetter("krish21an"))

Most Popular

Recent Comments