Search code examples
androidapiloopskotlinline

Looping in kotlin in line


i have some trouble in using kotlin for looping

i have json as like below :

{
idEvent: "584412",
strEvent: "Huesca vs Girona",
strHomeYellowCards: "28':Ezequiel Avila;34':Juan Nunez Aguilera;45':Damian Musto;88':David Ferreiro;"
}

and after i generate in android studio, i want the line strHomeYellowCards become like below in only one TextView:

Ezequiel Avila 28'
Juan Nunez Aguilera 34'
Damian Musto 45' 
David Ferreiro 88'

and these my code to make it happened

fun formatNumPlayer(players: String?): String {
        if (players.isNullOrBlank()) {
            return players.orEmpty()
        } else {
            val entered = players!!.replace(";", "\n")
            val splitted = entered!!.split(":")
            var result: String? = null
            for (i in splitted.indices) {
                result += "${splitted[1]}" + " " + "${splitted[0]}" + "\n"
            }
            return result!!
        }
    }

but the result is under my expectation, so how the true code about it?


Solution

  • The JSON provided is not a well formatted JSON. So i assume that you just pasted the key:value pair here.

    In this case, taking the value as a string and processing it would be the easiest way to achieve your goal.

    // Assume bulkText is the value of key `strHomeYellowCards`
    val bulkText = "28':Ezequiel Avila;34':Juan Nunez Aguilera;45':Damian Musto;88':David Ferreiro;"
    
    var result = ""
    
    bulkText.split(';').forEach{
        result += it.split(':').asReversed().reduce{ sum, element -> sum + ' ' + element } + '\n'
    }
    
    // result should be your desired output
    println(result)