string - scala中的splitAt '-'

标签 string scala higher-order-functions

我需要返回两个列表,字符串列表直到并包括包含“-”的第一行,然后是其余元素。

所以我一直在尝试 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/

相关文章:

Java:在 String 对象上同步

c++ - 如何获取卫星资源 DLL 的模块句柄? (C++ Visual Studio )

python - 如何检查一个单词是否适合指定数量的列?

scala - 拆分 Play ! 2 应用成模块

函数式编程公理

c - 从长度未知的字符串中读取所有 double

scala - 找不到spark-sql中的聚合函数

scala - 在for循环chisel3中使用yield时如何访问前一个元素

haskell - 用 foldr 构建平衡二叉树

android - 预览中不支持具有非默认参数的可组合函数,除非它们使用 @PreviewParameter 注释