Sobes.tech
Intern

How to reverse a string?

sobes.tech AI

Answer from AI

  1. Iteration with creating a new string:
// Example of reversing a string
fun reverseString(str: String): String {
    var reversed = ""
    for (i in str.length - 1 downTo 0) {
        reversed += str[i]
    }
    return reversed
}
  1. Using StringBuilder/StringBuffer:
// Example of reversing a string using StringBuilder
fun reverseString(str: String): String {
    return StringBuilder(str).reverse().toString()
}
  1. Using string methods (Kotlin):
// Example of reversing a string using reversed()
fun reverseString(str: String): String {
    return str.reversed()
}
  1. Recursion:
// Example of recursive string reversal
fun reverseString(str: String): String {
    return if (str.isEmpty()) {
        str
    } else {
        reverseString(str.substring(1)) + str[0]
    }
}

The choice of method depends on performance requirements, code readability, and the need to support older Java versions (when using StringBuilder/StringBuffer). The reversed() method in Kotlin is the most concise and preferred.