如何从右侧通过分隔符分割字符串?

问题描述 投票:0回答:4

如何从右边用分隔符分割字符串?

例如

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

Python 有一个

.rsplit()
方法,这就是我在 Scala 中所追求的:

In [1]: "hello there how are you?".rsplit(" ", 1)
Out[1]: ['hello there how are', 'you?']
scala
4个回答
16
投票

我认为最简单的解决方案是搜索索引位置,然后基于该位置进行拆分。例如:

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)

5
投票

您可以使用普通的旧正则表达式:

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
投票
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?)

0
投票

迭代使用

lastIndexOf
substring
进行分割。

object Main {
  def rsplit(string: String, delimiter: String, maxSplits: Int): Array[String] = {
    var remainingSplits = maxSplits
    var str = string
    var result = List[String]()

    while (remainingSplits > 0) {
      val pos = str.lastIndexOf(delimiter)
      if (pos == -1) {
        result = str :: result
        remainingSplits = 0
        str=""
      } else {
        result = str.substring(pos + delimiter.length) :: result
        str = str.substring(0, pos)
        remainingSplits -= 1
      }
    }

    if (str.nonEmpty || maxSplits == 0) {
      result = str :: result
    }

    result.toArray
  }

  def myPrint(stringArray: Array[String]): Unit= {
    println("["++stringArray.map("\'"++_++"\'").mkString(", ")++"]");
  }

  def main(args: Array[String]): Unit = {
    // Test cases
    myPrint(rsplit("bor tor tor tor", "tor", 2))  // More than maxSplits
    myPrint(rsplit("bor tor tor", "tor", 2))      // Exactly equal to maxSplits
    myPrint(rsplit("bor tor", "tor", 2))      // Less than maxSplits
  }
}

在线尝试!

© www.soinside.com 2019 - 2024. All rights reserved.