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

Kotlin | Operations on String Array: Here, we are going to learn how to perform read, traverse, reverse and sorting operations on a string array in Kotlin programming language? Submitted by IncludeHelp, on May 03, 2020

Kotlin - Read, traverse, reverse, and sort string array

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"]

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] : New Delhi
strArray[2] : Australia
strArray[3] : Corona
strArray[4] : Ameriaca
strArray[5] : Japan
strArray[6] : mumbai
String Array Elements : [includehlep indai, New Delhi, Australia, Corona, Ameriaca, Japan, mumbai]
Reversed String Array Elements : [mumbai, Japan, Ameriaca, Corona, Australia, New Delhi, includehlep indai]
Sorted String Array Elements : [Ameriaca, Australia, Corona, Japan, New Delhi, includehlep indai, mumbai]
Sorted String Array Elements : [mumbai, includehlep indai, New Delhi, Japan, Corona, Australia, Ameriaca]

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.