Kotlin function: Reverse a string
Kotlin Function: Exercise-4 with Solution
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/kotlin-exercises/function/kotlin-function-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics