Scala:绘制表格到控制台 [英] Scala: Draw table to console
本文介绍了Scala:绘制表格到控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在控制台中显示一个表。
I need to display a table in a console.
如果您将其称为解决方案,我的简单解决方案如下:
My simple solution, if you would call it a "solution", is as follows:
override def toString() = {
var res = "\n"
var counter = 1;
res += stateDb._1 + "\n"
res += " +----------------------------+\n"
res += " + State Table +\n"
res += " +----------------------------+\n"
for (entry <- stateDb._2) {
res += " | " + counter + "\t | " + entry._1 + " | " + entry._2 + " |\n"
counter += 1;
}
res += " +----------------------------+\n"
res += "\n"
res
}
我们不必为此争辩
- a显示时看起来很糟糕
- b代码看起来有点混乱
实际上,这样的问题被要求使用C#,但我也想知道一个适用于Scala的不错的解决方案
Actually, such a question was asked for C# but I would like to know a nice solution for Scala as well.
那么在Scala中向控制台绘制这样一张表的一种(好/好/简单/任何)方式是什么?
So what is a (nice/good/simple/whatever) way to draw such a table in Scala to the console?
-------------------------------------------------------------------------
| Column 1 | Column 2 | Column 3 | Column 4 |
-------------------------------------------------------------------------
| | | | |
| | | | |
| | | | |
-------------------------------------------------------------------------
推荐答案
我从当前项目中删除了以下内容:
I've pulled the following from my current project:
object Tabulator {
def format(table: Seq[Seq[Any]]) = table match {
case Seq() => ""
case _ =>
val sizes = for (row <- table) yield (for (cell <- row) yield if (cell == null) 0 else cell.toString.length)
val colSizes = for (col <- sizes.transpose) yield col.max
val rows = for (row <- table) yield formatRow(row, colSizes)
formatRows(rowSeparator(colSizes), rows)
}
def formatRows(rowSeparator: String, rows: Seq[String]): String = (
rowSeparator ::
rows.head ::
rowSeparator ::
rows.tail.toList :::
rowSeparator ::
List()).mkString("\n")
def formatRow(row: Seq[Any], colSizes: Seq[Int]) = {
val cells = (for ((item, size) <- row.zip(colSizes)) yield if (size == 0) "" else ("%" + size + "s").format(item))
cells.mkString("|", "|", "|")
}
def rowSeparator(colSizes: Seq[Int]) = colSizes map { "-" * _ } mkString("+", "+", "+")
}
scala> Tabulator.format(List(List("head1", "head2", "head3"), List("one", "two", "three"), List("four", "five", "six")))
res1: java.lang.String =
+-----+-----+-----+
|head1|head2|head3|
+-----+-----+-----+
| one| two|three|
| four| five| six|
+-----+-----+-----+
这篇关于Scala:绘制表格到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文