Kotlin function: Reverse a string
Write a Kotlin function that reverses a given string.
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.
Kotlin Editor:
Previous: Count vowels in a string.
Next: Check if a string is a palindrome.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics