首页 > 代码库 > 计算每行所占字符个数,并格式化输出

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

import scala.io.Sourcedef 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")

技术分享

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