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")
    }
     
  • 相关阅读:
    赫尔维茨公式
    从解析几何的角度分析二次型
    Struts 1 Struts 2
    记一次服务器被入侵的调查取证
    契约式设计 契约式编程 Design by contract
    lsblk df
    Linux Find Out Last System Reboot Time and Date Command 登录安全 开关机 记录 帐号审计 历史记录命令条数
    Infrastructure for container projects.
    更新文档 版本控制 多版本并发控制
    Building Microservices: Using an API Gateway
  • 原文地址:https://www.cnblogs.com/studyLog-share/p/4732875.html
Copyright © 2011-2022 走看看