如何基于定界符将字符串分为2个不同的变量?

问题描述 投票:-2回答:1

我使用split函数将一个变量一分为二。现在,我想将split变量存储为2个不同的变量。例如,我将字符串“ input”分为两部分。现在,我将分隔符为正斜杠的变量进行了拆分。我想将斜杠之前的文本存储为“ pre_input”,并将斜杠之后的文本存储为“ post_input”。我该怎么做呢?请也提供一些代码,我将不胜感激。

android android-studio kotlin
1个回答
0
投票

分割字符串时,它将返回一个数组。您需要做的就是从数组中获取每个元素。

注意:如果您不知道要输入什么,可能会很危险,请考虑检查结果的实际长度。

val input = "before/after"

// Split will return an array
val split = input.split("/")

val before = split[0] // First element
val after = split[1] // Second element
© www.soinside.com 2019 - 2024. All rights reserved.