简体   繁体   English

从 Kotlin 中的列表或哈希映射数组列表拆分字符串

[英]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我在 Json 列表中有这个输出,我想在我的应用程序中使用这个列表的值

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)?我想得到例如字符串中的 E 和 -2 将其用作公式中的数字。如何提取这些实体中的每一个并将它们放入变量(E 和 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.但是,如果您想将所有 E_ 值添加到一个变量中,并将所有 I_ 值添加到另一个变量中,您可以使用正则表达式来完成,而无需制作任何列表或地图或其他对象,只需使用您得到的字符串。

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在这种情况下, e将是 5, i将是 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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