A. *_*ini 6 java arrays string android kotlin
我想将字符串转换为数组或字符串或字符列表,例如:Array<String>或Array<Char>。
例子:
\nval myText = "Ab+2#\xe2\x9c\x85'\xc3\xbc{" // Parse and print to Log\nRun Code Online (Sandbox Code Playgroud)\n应该:
\n[ "A", "b", "", "+", "", "2", "", "#", "\xe2\x9c\x85", "'", "", "\xc3\xbc", "", "{" ] // Array contains Strings or Chars\nRun Code Online (Sandbox Code Playgroud)\nJava/Kotlin 方法由于 Android 上的表情符号而不起作用:
\nmyText.toList() // \xe2\x9d\x8c Fails because of Emojis\nmyText.toMutableList() // \xe2\x9d\x8c Fails because of Emojis\nRun Code Online (Sandbox Code Playgroud)\n
在 Kotlin 中,如果面向 JDK 8 或更高版本,您可以使用:
fun String.splitToCodePoints(): List<String> {
return codePoints()
.toList()
.map { String(Character.toChars(it)) }
}
Run Code Online (Sandbox Code Playgroud)
如果使用 JDK 7,则需要更多手动操作:
fun String.splitToCodePoints(): List<String> {
val list = mutableListOf<String>()
var count = 0
while (count < length) {
with (codePointAt(count)){
list.add(String(Character.toChars(this)))
count += Character.charCount(this)
}
}
return list
}
Run Code Online (Sandbox Code Playgroud)
看来 Kotlin 标准库在这些方面有所欠缺,因为您必须依赖 JDK 装箱原始类将代码点整数转换为字符串。
正如此处另一个答案中提到的,如果您需要处理零宽度连接器,则必须更多地参与其中。您可能需要删除任何零宽度连接符,以便可以单独显示字符,或者您可能希望将它们一起显示,因此需要操作列表以组合由连接符分隔的元素。如果该语言使用连字,这会影响这个决定。