Split space from string not working in Kotlin

僤鯓⒐⒋嵵緔 提交于 2019-12-04 02:27:30

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

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];

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

value.split(" ")[0];

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.

You need to use :

.toRegex()

fun main(args: Array<String>) {
        val str = "Kotlin com"

        val separate1 = str.split("\\s".toRegex())[0]
        println(separate1) // ------------------> Kotlin
}

OR

You can also use .split(" ")[0] to achieve result. Like

fun main(args: Array<String>) {
            val str = "Kotlin com"

            val separate1 = str.split(" ")[0]
            println(separate1) // ----------> Kotlin
}

String#split (actually CharSequence#split) can take either a regular expression, or just a string which is interpreted literally. So:

value.split(" ")[0]

does what you want.

If you're only using the first element, it's more efficient to also pass limit = 2. Or, even better, use substringBefore.

Kotlin tries to resolve some issues that Java's String library has. For instance, Kotlin tries to be more explicit.

As a result, the split method takes a normal String and does not use it as a regex internally:

"hello world".split("\\s")[0] //no match
"hello world".split(" ")[0] // => "hello"

To explicitly use the overloaded split function that actually takes a regex, the toRegex() extension can be used (inline fun String.toRegex(): Regex (source)):

"hello world".split("\\s".toRegex())[0]// => "hello"

The following shows another example of Kotlin resolving the confusing String::replaceAll method:

Taken from a KotlinConf presentation of Svetlana Isakova, co-author of “Kotlin in Action”

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!