Split space from string not working in Kotlin
Asked Answered
T

6

30

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

Tried with this :

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

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?

Solution : As @Edson Menegatti said :

KOTLIN Specific : WORKING

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

Many people suggested this solution : NOT WORKING

values.split(" ")[0] 

But in my case it's not working.

Trepang answered 22/1, 2018 at 10:57 Comment(2)
you don't need semicolon, btw.Incommunicable
its a java code actually. :P i mentioned that i came up with this solution. ;)Trepang
M
58

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.

Malonylurea answered 22/1, 2018 at 11:3 Comment(1)
This is so stupid. I get why but this doesn't make it easy to go from java -> kotlin.Unprintable
C
13

You should 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
}
Crispy answered 22/1, 2018 at 11:4 Comment(0)
A
5

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.

Adamsite answered 22/1, 2018 at 11:1 Comment(6)
Your assertion is it not true, String.split() can also take a regex, a pattern...Argil
Thanks @AlexTa, edited. I failed to scroll down far enough.Adamsite
No this thing is not working in kotlin, i already tried with thisTrepang
@BabulPatel If you say something is "not working", always provide the code you tried, and the error message and expected and actual output. Paste println("Hello, world!".split(" ")[0]) into the main function at try.kotlinlang.org/#/Examples/Hello,%20world!/… and see it print Hello, as desired.Adamsite
this function doen't split the string. It actually returns the string as it is. @AdamsiteTrepang
Then I must conclude that the character in your string is not a space.Adamsite
S
2

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:

enter image description here

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

Songful answered 22/1, 2018 at 11:13 Comment(0)
W
2

Single delimiter

 val splittedStringList = "123.345-80A".split(".")
 println(splittedStringList[0])

Several delimiters

 println("123.345-80A".split(".", "-"))

Using regex

 println("123.345-80A".split("\\.|-".toRegex()))

Try Kotlin Online

Washstand answered 21/2, 2020 at 11:30 Comment(0)
F
1

Simply use value.split("\s".toRegex())

1.Splits and iterates all items

value.split("\\s".toRegex()).forEach { item ->
    //use item 
}

2.Spits and use first item

value.split("\\s".toRegex()).first()

3.Spits and use last item

value.split("\\s".toRegex()).last()
Forras answered 21/2, 2020 at 11:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.