Q:

Kotlin program to read, traverse, reverse and sort string array

belongs to collection: Kotlin Array Programs

0

Given a string array, we have to read, traverse, reverse and sort its elements.

Example:

    Input:
    arr = ["abc", "pqr", "xyz"]

    Output:
    String arra is: ["abc", "pqr", "xyz"]
    Reversed: ["xyz", "pqr", "abc"]
    Sorted (Ascending Order): ["abc", "pqr", "xyz"]
    Sorted (Descending Order): ["xyz", "pqr", "abc"]

All Answers

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

Program to read, traverse, reverse and sort string array in Kotlin

package com.includehelp.basic

import java.util.*

//Main Function entry Point of Program
fun main(args: Array<String>) {
    //Input Stream
    val s = Scanner(System.`in`)

    //Input Array Size
    print("Enter number of elements in the String array: ")
    val size = s.nextInt()

    //Create Integer array of Given size
    val strArray = Array<String>(size){""}

    //Input array elements
    println("Enter String Arrays Elements:")
    for (i in strArray.indices) {
        print("strArray[$i] : ")
        strArray[i] = readLine().toString()
    }

    //Print String Array
    println("String Array Elements : ${strArray.contentToString()}")

    //Print String Array in Reverse
    var reversedArray = strArray.reversedArray()
    println("Reversed String Array Elements : ${reversedArray.contentToString()}")

    //Print Ascending Sorted Array
    var ascSortedArray = strArray.sortedArray()
    println("Sorted String Array Elements : ${ascSortedArray.contentToString()}")

    //Print Descending Sorted Array
    var desSortedArray = strArray.sortedArrayDescending()
    println("Sorted String Array Elements : ${desSortedArray.contentToString()}")
}

Output

Enter number of elements in the String array: 7
Enter String Arrays Elements:
strArray[0] : includehlep indai
strArray[1] : Nee Delhi
strArray[2] : Australia
strArray[3] : Corona
strArray[4] : Ameriaca
strArray[5] : Japan
strArray[6] : mumbai
String Array Elements : [includehlep indai, Nee Delhi, Australia, Corona, Ameriaca, Japan, mumbai]
Reversed String Array Elements : [mumbai, Japan, Ameriaca, Corona, Australia, Nee Delhi, includehlep indai]
Sorted String Array Elements : [Ameriaca, Australia, Corona, Japan, Nee Delhi, includehlep indai, mumbai]
Sorted String Array Elements : [mumbai, includehlep indai, Nee Delhi, Japan, Corona, Australia, Ameriaca]

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

total answers (1)

Kotlin program to find largest element in an array... >>
<< Kotlin program to sort an array in descending orde...