scala逗号分隔字符串到双引号逗号分隔字符串

  • 本文关键字:字符串 分隔 scala scala
  • 更新时间 :
  • 英文 :


我有一个文件,其中包含某些字符串,如-

Apple
Google
Microsoft

我正在以的身份阅读此文件

val lines = scala.io.Source.fromFile(filePath).mkString.replace("n", ",")

这会产生一个逗号分隔的字符串列表。然而,我真正想要的是"Apple","Google","Microsoft"

如果我在字符串中添加双引号,则在读取文件时替换,我必须处理第一个和最后一个双引号,这并不理想。我该怎么做?

一个选项是将每一行加载到Iterator中,然后让mkString应用逗号和引号。

io.Source
.fromFile(filePath)
.getLines()
.mkString(""","","",""")
//res0: String = "Apple","Google","Microsoft"

类似于jwvh的答案,但使用Using进行资源管理

import scala.util.Using
import scala.io.Source
Using.resource(Source.fromFile(filePath)) { file =>
file.getLines.map(line => s""""$line"""").mkString(",")
}

最新更新