【问题标题】:Crystal get from n line to n line from a fileCrystal 从文件中获取第 n 行到第 n 行
【发布时间】:2018-07-18 11:20:40
【问题描述】:

如何获取文件中的特定行并将其添加到数组中?

例如:我想获取第 200-300 行并将它们放入一个数组中。同时计算文件中的总行数。文件可能很大。

【问题讨论】:

    标签: crystal-lang


    【解决方案1】:

    File.each_line 是一个很好的参考:

    lines = [] of String
    index = 0
    range = 200..300
    
    File.each_line(file, chomp: true) do |line|
      index += 1
      if range.includes?(index) 
        lines << line
      end
    end
    

    现在lines 保存range 中的行,index 是文件中的总行数。

    【讨论】:

      【解决方案2】:

      为防止读取整个文件并为其所有内容分配一个新数组,您可以使用File.each_line 迭代器:

      lines = [] of String
      
      File.each_line(file, chomp: true).with_index(1) do |line, idx|
        case idx
        when 1...200  then next          # ommit lines before line 200 (note exclusive range)
        when 200..300 then lines << line # collect lines 200-300
        else break                       # early break, to be efficient
        end
      end
      

      【讨论】:

      • 这里不计算总行数。
      • @felixbuenemann 你是对的,我误读了问题的那一部分。
      猜你喜欢
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2015-10-28
      • 2012-08-21
      相关资源
      最近更新 更多