Kotlin String - reversed() Function



The Kotlin string reversed() function is used to reverse the characters of a string and return a new string containing characters of this string in reverse order.

The use cases of this function are Text formatting, Data manipulation, Puzzle solver, or encryption and encoding.

The reversed() function does not modify the string; it creates a new string in the reverse order. It is case-sensitive and retains all characters in their revered order, including spaces and symbols.

Syntax

Following is the syntax of the Kotlin string reversed() function −

fun CharSequence.reversed(): String

Parameters

This function does not accepts any parameters.

Return value

This function returns a string.

Example 1: Reverse a String

Following is the basic example of the reversed() function −

fun main() {
   val input_str = "tutorialspoint"
   // reverse the string
   val output_str = input_str.reversed()
   println("Reversed string: " + output_str)
}

Output

Following is the output −

Reversed string: tniopslairotut

Example 2: Validate Palindromic String

In this example, we use the revered() to check whether the input string is palindromic or not. If the string is palindromic then the reverse string will be the same −

fun main() {
   val str = "madam"
   // reverese the string
   val result = str.reversed()
   println("reversed string: "+result)
   println("Original string: "+str)
}

Output

Following is the output −

reversed string: madam
Original string: madam

Example 3: Reversing Strings with Digits

If the string contains a digit, then thereversed()function will reverse the character or not −

fun main(args: Array<String>) {
   val str = "45tutorialspoint56"
   // reverese the string
   val result = str.reversed()
   println("reversed string: "+result)
   println("Original string: "+str)
}

Output

Following is the output −

reversed string: 32tniopslairotut23
Original string: 32tutorialspoint23
kotlin_strings.htm
Advertisements