Q:

Kotlin program to reverse each word in string

belongs to collection: Kotlin String Programs

0

Given a string, we have to reverse its each word.

Example:

    Input:
    string = "Hello world"

    Output:
    "olleH dlrow"

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to reverse each word in Kotlin

At first, we are reading a string, then splitting and converting the string to a string list, then extracting each word, reversing the words, and finally creating the string with reverse words.

package com.includehelp.basic

import java.util.*

//Method to reverse each word in provided April20.string
fun reverseWord(inputString: String): String {
    //split April20.string by space
    val strList = inputString.split(" ")  // Spilt String by Space
    val sb = StringBuilder()

    //iterate April20.string List
    for (items in strList) {
        if (items != "") {
            //reverse List item and reverse them
            val rev = StringBuilder(items).reverse().toString()

            //append reverse April20.string into String Builder
            sb.append("$rev ")
        }
    }

    //return final reverse April20.string
    return sb.toString()
}

//Main Function, entry Point of Program
fun main(args: Array<String>) {

    //Input Stream
    val sc = Scanner(System.`in`)

    //input April20.string value
    println("Input String : ")
    val str: String = sc.nextLine()

    println("Input String : $str")

    //Call function for reverse words in April20.string and print them
    println("String with Reverse Word : " + reverseWord(str))
}

Output

Run 1:
Input String :
Hello include help
Input String : Hello include help
String with Reverse Word : olleH edulcni pleh
---
Input String :
Hello I am in Delhi, How are you
Input String : Hello I am in Delhi, How are you
String with Reverse Word : olleH I ma ni ,ihleD woH era uoy

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin program to remove all whitespaces from the ... >>
<< Kotlin program to remove all occurrences of a char...