How to split a string by a delimiter from the right?
e.g.
scala> "hello there how are you?".rightSplit(" ", 1)
res0: Array[java.lang.String] = Array(hello there how are, you?)
Python has a .rsplit()
method which is what I'm after in Scala:
In [1]: "hello there how are you?".rsplit(" ", 1)
Out[1]: ['hello there how are', 'you?']
You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe.
Use str. split() to convert a comma-separated string to a list. Call str. split(sep) with "," as sep to convert a comma-separated string into a list.
You can split the data by using a common delimiter character. A delimiter character is usually a comma, tab, space, or semi-colon. This character separates each chunk of data within the text string. A big advantage of using a delimiter character is that it does not rely on fixed widths within the text.
I think the simplest solution is to search for the index position and then split based on that. For example:
scala> val msg = "hello there how are you?"
msg: String = hello there how are you?
scala> msg splitAt (msg lastIndexOf ' ')
res1: (String, String) = (hello there how are," you?")
And since someone remarked on lastIndexOf
returning -1, that's perfectly fine with the solution:
scala> val msg = "AstringWithoutSpaces"
msg: String = AstringWithoutSpaces
scala> msg splitAt (msg lastIndexOf ' ')
res0: (String, String) = ("",AstringWithoutSpaces)
You could use plain old regular expressions:
scala> val LastSpace = " (?=[^ ]+$)"
LastSpace: String = " (?=[^ ]+$)"
scala> "hello there how are you?".split(LastSpace)
res0: Array[String] = Array(hello there how are, you?)
(?=[^ ]+$)
says that we'll look ahead (?=
) for a group of non-space ([^ ]
) characters with at least 1 character length. Finally this space followed by such sequence has to be at the end of the string: $
.
This solution wont break if there is only one token:
scala> "hello".split(LastSpace)
res1: Array[String] = Array(hello)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With