Given a string, reverse all of its characters and return the resulting string.
1 min read

Given a string, reverse all of its characters and return the resulting string.

Ex: Given the following strings...

“Cat”, return “taC”
“The Daily Byte”, return "etyB yliaD ehT”
“civic”, return “civic”

The String class is immutable in kotlin so we can't reverse the string in-place but we can store the reversed value in another string.

1.  Using reversed() Function

The standard way to reverse the string is to use the reversed function which returns the string in reverse order.

fun main() {
    val stringToReverse = "Cat"
    val reversedString = stringToReverse.reversed()
  
    print("String reversed is: " + reversedString)
}

2. Using Recursion

On each iteration, we add (concatenate) the result of next reverse() function to the first character of sentence using charAt(0).

fun main() {
    val stringToReverse = "Cat"
    val reversedString = reversed(stringToReverse)
  
    print("String reversed is: " + reversedString)
}


fun reverse(value: String) : String {
	if(value.isEmpty())
    return value
    
    return reverse(value.substring(1)) + value[0]
}

3. Using CharArray

The idea here is to create an empty char array of the same size as the string and then fill the characters in reverse order. We then convert the char Array to String.

fun main() {
    var stringValue = "Cat iS"
    var reversedString = reverse(stringValue)
    print(reversedString)
}

fun reverse(value: String): String {
    val charArray = CharArray(value.length)
    value.indices.forEach {
        charArray[value.length-it-1] = value[it]
    }
    return String(charArray)   
}