从字符串拆分空间在 Kotlin 中不起作用 [英] Split space from string not working in Kotlin

查看:22
本文介绍了从字符串拆分空间在 Kotlin 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人想知道这个吗?在 kotlin 中拆分 SPACE (" ") 不起作用,我尝试使用不同的正则表达式代码,但根本不起作用.

Anyone wonder this ? Splitting SPACE (" ") in kotlin is not working, i tried with different regex codes but is not working at all.

试过这个:

value.split("\\s")[0];
value.split("\\s+")[0];
value.split("\\s++")[0];

然后我想出了解决方案 -> 创建包含此函数的 java 常量类并将字符串数组返回到您的 kotlin 类.

Then i came up with solution -> Create java constant class which contains this function and returns string array to your kotlin class.

对于这个问题,有没有其他解决方案可以直接实现这个东西?

Is there any other solution for this problem where we can directly achieve this thing?

解决方案:正如@Edson Menegatti 所说:

Solution : As @Edson Menegatti said :

KOTLIN 特定:有效

values.split("\\s".toRegex())[0]

许多人提出了这个解决方案:不起作用

Many people suggested this solution : NOT WORKING

values.split(" ")[0] 

但就我而言,它不起作用.

推荐答案

这是 String.split 的 Java 和 Kotlin 实现之间的问题.

Here's an issue between the Java and Kotlin implementation of String.split.

虽然 Java 实现确实接受正则表达式字符串,但 Kotlin 实现不接受.要使其正常工作,您需要提供一个实际的 Regex 对象.

While the Java implementation does accept a regex string, the Kotlin one does not. For it to work, you need to provide an actual Regex object.

为此,您需要按如下方式更新您的代码:

To do so, you would update your code as follows:

value.split("\\s".toRegex())[0]

此外,正如@Thomas 所建议的,您可以只使用常规空格字符来分割您的字符串:

Also, as @Thomas suggested, you can just use the regular space character to split your string with:

value.split(" ")[0]

最后一点,如果您只使用拆分列表的第一个元素,您可能需要考虑使用 first() 而不是 [0] - 对于更好的可读性 - 并将限制参数设置为 2 - 以获得更好的性能.

Final point, if you're only using the first element of the split list, you might want to consider using first() instead of [0] - for better readability - and setting the limit parameter to 2 - for better performance.

这篇关于从字符串拆分空间在 Kotlin 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆