Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split space from string not working in Kotlin

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.

like image 682
Harsh Patel Avatar asked Jan 22 '18 10:01

Harsh Patel


People also ask

How do you split a string by space in Kotlin?

We can use the split() function to split a char sequence around matches of a regular expression. To split on whitespace characters, we can use the regex '\s' that denotes a whitespace character. Note that we have called the toTypedArray() function, since the split() function returns a list.

How do you cut space in Kotlin?

There are several whitespace characters in Kotlin. The most common is space, \t , \n , and \r . The pattern for matching whitespace characters is \s . To remove all whitespace from the input string, you should use the pattern \s and replace the matches with an empty string.

Is substring in Kotlin?

The Kotlin way to check if a string contains a substring is with the In operator, which provides shorter and more readable syntax. The expression a in b is translated to b. contains(a) and the expression a !in b is translated to !


1 Answers

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.

like image 55
Edson Menegatti Avatar answered Oct 05 '22 14:10

Edson Menegatti