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.
String#split
(actuallyCharSequence#split
) can take either a regular expression, or just a string which is interpreted literally. So:does what you want.
If you're only using the first element, it's more efficient to also pass
limit = 2
. Or, even better, usesubstringBefore
.You need to use :
OR
You can also use
.split(" ")[0]
to achieve result. LikeHere'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:
Also, as @Thomas suggested, you can just use the regular space character to split your string with:
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.Single delimiter
Several delimiters
Using regex
Try Kotlin Online
Simply use value.split("\s".toRegex())
1.Splits and iterates all items
2.Spits and use first item
3.Spits and use last item
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 normalString
and does not use it as a regex internally:To explicitly use the overloaded
split
function that actually takes a regex, thetoRegex()
extension can be used (inline fun String.toRegex(): Regex (source)
):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”