How to Reverse Letters in Kotlin

0 min read 113 words

The challenge

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

Examples:

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

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

Input/Output:

  • [input] string str

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

  • [output] a string

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 {
  @Test
  fun `Basic Tests` () {
    val str = "krishan"
    assertEquals("nahsirk", reverseLetter("krishan"))
    assertEquals("nortlu", reverseLetter("ultr53o?n"))
    assertEquals("cba", reverseLetter("ab23c"))
    assertEquals("nahsirk", reverseLetter("krish21an"))
  }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags