2013-04-02 61 views
5

如何從右側的分隔符分割字符串?如何從右側分隔字符串?

例如

scala> "hello there how are you?".rightSplit(" ", 1) 
res0: Array[java.lang.String] = Array(hello there how are, you?) 

Python有一個.rsplit()方法這是我後我在斯卡拉:

In [1]: "hello there how are you?".rsplit(" ", 1) 
Out[1]: ['hello there how are', 'you?'] 

回答

12

我認爲最簡單的辦法是尋找基於該指數的位置,然後分裂。例如:

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?") 

而且,由於有人在lastIndexOf返回-1說,這是與解決方案完美的罰款:

scala> val msg = "AstringWithoutSpaces" 
msg: String = AstringWithoutSpaces 

scala> msg splitAt (msg lastIndexOf ' ') 
res0: (String, String) = ("",AstringWithoutSpaces) 
+4

'lastIndexOf'可以返回'-1'。 – huynhjl

+1

@huynhjl在這種情況下,splitAt將首先返回一個空字符串,其次是原始字符串。 –

+0

當你想到了一切!你是對的,它的工作原理。 – huynhjl

4

你可以使用普通的老正則表達式:

scala> val LastSpace = " (?=[^ ]+$)" 
LastSpace: String = " (?=[^ ]+$)" 

scala> "hello there how are you?".split(LastSpace) 
res0: Array[String] = Array(hello there how are, you?) 

(?=[^ ]+$)說我們會向前看(?=)一組非空間([^ ])字符,至少有1個字符長度。最後,這個序列後面的空格必須位於字符串的末尾:$

該解決方案不會打破,如果只有一個令牌:

scala> "hello".split(LastSpace) 
res1: Array[String] = Array(hello) 
+1

我認爲是建議使用正則表達式,但與我最終提出的更簡單的方法相比,效率更低,更難以理解。不要在你的解決方案上施加影響 - 這是完全可行的,並且與其他方案完全不同 - 但我想知道複雜解決方案是什麼讓人們更喜歡它們? –

1
scala> val sl = "hello there how are you?".split(" ").reverse.toList 
sl: List[String] = List(you?, are, how, there, hello) 

scala> val sr = (sl.head :: (sl.tail.reverse.mkString(" ") :: Nil)).reverse 
sr: List[String] = List(hello there how are, you?)