w3resource

Kotlin function: Reverse a string


Write a Kotlin function that reverses a given string.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • String Manipulation.
  • Printing Output.

Hints (Try before looking at the solution!)

  • Define the Function.
  • Use Built-in Functions.
  • Return the Result.
  • Display the Output.
  • Test with Different Strings.
  • Common Errors to Avoid:
    • Forgetting to return the reversed string.
    • Misusing the reversed() function.
    • Not handling edge cases correctly.

Sample Solution:

Kotlin Code:

fun reverseString(input: String): String {
    return input.reversed()
}

fun main() {
    val str = "Kotlin function."
    println("Original string: $str")
    val reversedStr = reverseString(str)
    println("Reversed string: $reversedStr")
}

Sample Output:

Original string: Kotlin function.
Reversed string: .noitcnuf niltoK

Explanation:

In the above exercise -

  • The "reverseString()" function takes a String parameter named input, representing the string to reverse.
  • The reversed() function is called on the input string, which returns the string with the characters in reverse order.
  • The reversed string is then returned as the function result.
  • In the main function, a sample string str is defined.
  • The reverseString function is called with the string as an argument, and the result is stored in the 'reversedStr' variable.
  • Finally the reversed string is printed to the console.

Go to:


PREV : Count vowels in a string.
NEXT : Check if a string is a palindrome.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.