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

查看:83
本文介绍了从字符串拆分空间在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]-为了提高可读性-并将limit参数设置为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天全站免登陆