zoukankan      html  css  js  c++  java
  • Scala学习笔记(三):从文件里读取文本行

    第一版

    test-scala.sh文件内容如下:

    #!/bin/sh
    exec scala "$0" "$@"
    !#
    
    println("Hello, Welcome to https://www.iteblog.com!")
    
    args.foreach(println)
    
    import scala.io.Source
    if(args.length>0){
      for(line<-Source.fromFile(args(0)).getLines)
        println(line.length+" "+line)
    }else{
      Console.err.println("Please enter FileName")
    }

    运行上述代码(命令:sh test-scala.sh test-scala.sh),输出形式如下:

    从上图可以看出,行首的字符数影响了代码排版

    第二版 - 固定行首字符数所占的宽度

    预期得到如下效果图:

    思路:

    1)定义widthOfLength方法用于计算行宽

    2)找到最长的一行

    3)将该行字符串传给widthOfLength,得到最大宽度

    import scala.io.Source
    def widthOfLength(s:String)=s.length.toString.length
    if(args.length>0){
      val lines=Source.fromFile(args(0)).getLines.toList
      var maxWidth=0
      for(line<-lines)
        maxWidth=maxWidth.max(widthOfLength(line))
      for(line<-lines){
        val numSpaces=maxWidth-widthOfLength(line)
        val padding=" "*numSpaces
        println(padding+line.length+"|"+line)
      }
    }else{
      Console.err.println("Please enter FileName")
    }

    第三版

    Scale属于 OOP 与 FP 混合的编程语言,在函数式编程中不推荐使用var

    import scala.io.Source
    def widthOfLength(s:String)=s.length.toString.length
    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")
    }
     
  • 相关阅读:
    s3c2440的2440init.s的分析(转载)
    sql server错误状态列表(转载)
    vector类、迭代器、bitset类(转载)
    VC++以ADO方式连接SQL SERVER
    WinCE流设备驱动简介及GPIO驱动的实现(转载)
    .obj, .lib, .dll, .exe的关系(转载)
    利用DynamicExpression.ParseLambda实现Eval
    Matching Balanced Constructs with .NET Regular Expressions
    VB.NET and C# Comparison【转】
    ReportViewer一个简单例子
  • 原文地址:https://www.cnblogs.com/studyLog-share/p/4732875.html
Copyright © 2011-2022 走看看