简体   繁体   中英

Split String from list or hash map array list in Kotlin

I have this output in Json list and I want use the Values of this list in my app

val dataOfTestToJson =  Gson().toJson(maps)
//I want this
E = 2 + 0 + 2 + 1
I = 2 + 0

// this is output

[{"Q1":"E_2"},{"Q2":"E_0"},{"Q3":"E_2"},{"Q4":"I_2"},{"Q5":"I_0"},{"Q6":"E_1"}]

I want to get For example E in String and -2 Use it as a number in the formula.How can I extract each of these entities and place them in the variables(E and I)?

I'm not entirely sure if this is what you mean. But if it's the case that you want to add up all E_ values into a variable and all I_ into another one you could do it with regex without the need of making any lists or maps or other objects and just use the string you got.

For example like this:

val response = """[{"Q1":"E_2"},{"Q2":"E_0"},{"Q3":"E_2"},{"Q4":"I_2"},{"Q5":"I_0"},{"Q6":"E_1"}]"""
val eRegex = Regex("E_(\\d+)")
val iRegex = Regex("I_(\\d+)")
val e = eRegex.findAll(response).map { it.groupValues[1].toInt() }.sum()
val i = iRegex.findAll(response).map { it.groupValues[1].toInt() }.sum()

e will be 5 and i will be 2 in this case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM