Kotlin String reversed()

Kotlin String reversed() Tutorial

The String.reversed() function in Kotlin is used to create a new string with the characters of the original string reversed. It returns a string with the order of characters reversed, making the last character of the original string the first character in the new string and vice versa.

In this tutorial, we’ll explore the syntax of the reversed() function and provide examples of its usage in Kotlin strings.

Syntax

The syntax of the reversed() function is as follows:

fun String.reversed(): String

The reversed() function is called on a string and returns a new string with the characters reversed.

Examples for String reversed() function

1. Reverse a given String using reversed()

In this example, we’ll use reversed() to reverse the characters of a simple string.

  1. Take a string value in originalString.
  2. Call reversed() function on originalString. The function returns a new string with the characters reversed.
  3. You may print the original and resulting strings to the console output.

Kotlin Program

fun main() {
    val originalString = "Hello, Kotlin!"

    // Using reversed() to reverse the characters of a string
    val resultString = originalString.reversed()

    // Printing the original and resulting strings
    println("Original String:\n$originalString\n")
    println("Reversed String:\n$resultString")
}

Output

Original String:
Hello, Kotlin!

Reversed String:
!nilt o ,olleH

2. Reverse an Empty String

In this example, we’ll use reversed() to reverse the characters of an empty string.

  1. Take an empty string value in emptyString.
  2. Call reversed() function on emptyString. The function returns an empty string since there are no characters to reverse.
  3. You may print the original and resulting strings to the console output.

Kotlin Program

fun main() {
    val emptyString = ""

    // Using reversed() to reverse the characters of an empty string
    val resultString = emptyString.reversed()

    // Printing the original and resulting strings
    println("Original String:\n$emptyString\n")
    println("Reversed String:\n$resultString")
}

Output

Original String:

Reversed String:

Summary

In this tutorial, we’ve covered the reversed() function in Kotlin strings, its syntax, and how to use it to create a new string with the characters of the original string reversed. This function is handy for scenarios where the order of characters needs to be reversed for further processing or display.