计算每行所占字符个数,并格式化输出

import scala.io.Source

def widthOfLength(s: String) = s.length.toString.length//计算字符串长度的位数,比如长度为:136,则位数为:3(三位数)
if (args.length > 0) {
    val lines = Source.fromFile(args(0)).getLines.toList
    val longestLine = lines.reduceLeft(
        (a, b) => if (a.length > b.length) a else b
    )
    val maxWidth = widthOfLength(longestLine)
    for (line <- lines) {
        val numSpaces = maxWidth - widthOfLength(line)
        val padding = " " * numSpaces
        println(padding + line.length + "|" + line)
    }
}else
    Console.err.println("Please enter filename")

image

posted @ 2015-01-04 17:18  竹 影 清 风  阅读(349)  评论(0编辑  收藏  举报