【问题标题】:scala comma separated string to double-quoted comma separated stringscala逗号分隔字符串到双引号逗号分隔字符串
【发布时间】:2020-02-21 08:19:23
【问题描述】:

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

Apple
Google
Microsoft

我在这个文件中阅读为

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

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

如果我在读取文件时在字符串替换中添加双引号,我同时必须注意第一个和最后一个双引号,这不是理想的。我该怎么办?

【问题讨论】:

    标签: scala


    【解决方案1】:

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

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

    【讨论】:

    • 我的输出现在看起来像 - "A","p","p","l","e".......
    • 您是否使用.getLines(并且仅.getLines)来读取文件?
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      • 2016-09-04
      相关资源
      最近更新 更多