Created
September 10, 2021 18:24
-
-
Save hakanai/853b607366a5f366d199a0f9b7ae76c0 to your computer and use it in GitHub Desktop.
Reversing a string in Kotlin 1.5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.text.BreakIterator | |
import java.text.StringCharacterIterator | |
fun reverse(string: String): String { | |
val iterator = BreakIterator.getCharacterInstance() | |
iterator.text = StringCharacterIterator(string) | |
val characters = mutableListOf<String>() | |
while (true) { | |
val startOffset = iterator.current() | |
if (iterator.next() == BreakIterator.DONE) { | |
break; | |
} | |
val endOffset = iterator.current() | |
val character = string.substring(startOffset, endOffset) | |
characters.add(character) | |
} | |
characters.reverse() | |
return characters.joinToString(separator = "") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment