Skip to content

How to Reverse Letters in Kotlin

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() }
Code language: Kotlin (kotlin)

Option 2:

fun reverseLetter(str: String) = str.reversed().filter{ it.isLetter() }
Code language: Kotlin (kotlin)

Option 3:

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

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")) } }
Code language: Kotlin (kotlin)

See also  Deconstruction in Kotlin
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x