Home »
Kotlin »
Kotlin programs »
Kotlin string programs
Kotlin program to reverse each word in string
Kotlin | Reversing each word in string: Here, we are going to learn how to reverse each words in the given string in Kotlin programming language?
Submitted by IncludeHelp, on April 29, 2020
Given a string, we have to reverse its each word.
Example:
Input:
string = "Hello world"
Output:
"olleH dlrow"
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