我需要返回两个列表,字符串列表直到并包括包含“-”的第一行,然后是其余元素。
所以我一直在尝试 lst.splitAt('-') 但它一直在做
scala> val lst = List(" Hi this is - a test")
lst: List[String] = List(" Hi this is - a test")
scala> lst.splitAt('-')
res8: (List[String], List[String]) = (List(" Hi this is - a test"),List())
我该如何解决这个问题,这样我才能得到 (List("Hi this is -),List(a test")) ?
最佳答案
List
的 splitAt 的参数是一个 Int
。您的“-”被强制为 45 并试图在索引 45 处拆分列表。
您可以对单个字符串执行此操作:
"hello-test-string".split('-')
这个(在 sbt 中)的结果是:
res0: Array[String] = Array(hello, test, string)
如果需要,您可以将此函数映射到字符串列表:
List("hello-test-string", "some-other-cool-string").map(_.split('-').toList)
这样的结果是:
res1: List[List[String]] = List(List(hello, test, string), List(some, other, cool, string))
关于string - scala中的splitAt '-',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26878760/