首页 > 解决方案 > 如何遍历字符串中的行?

问题描述

我在 Julia 中有一个很长的字符串。我想对每一行应用一些操作。如何有效地迭代每一行?我想我可以使用split,但我想知道是否有一种方法不会预先分配所有字符串?

标签: julia

解决方案


您可以eachline为此使用:

julia> str = """
       a
       b
       c
       """
"a\nb\nc\n"

julia> for line in eachline(IOBuffer(str))
         println(line)
       end
a
b
c

如果与您相关,还有一个直接在文件上运行的版本:

help?> eachline
search: eachline eachslice

  eachline(io::IO=stdin; keep::Bool=false)
  eachline(filename::AbstractString; keep::Bool=false)

  Create an iterable EachLine object that will yield each line from an I/O stream or a file. Iteration calls readline on
  the stream argument repeatedly with keep passed through, determining whether trailing end-of-line characters are
  retained. When called with a file name, the file is opened once at the beginning of iteration and closed at the end. If
  iteration is interrupted, the file will be closed when the EachLine object is garbage collected.

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> open("my_file.txt", "w") do io
             write(io, "JuliaLang is a GitHub organization.\n It has many members.\n");
         end;
  
  julia> for line in eachline("my_file.txt")
             print(line)
         end
  JuliaLang is a GitHub organization. It has many members.
  
  julia> rm("my_file.txt");

如果您已经在内存中拥有完整的字符串,那么您可以(并且应该)使用split,正如评论中所指出的那样。split基本上索引到字符串中,并且不会String为每一行分配新的 s,而不是eachline.


推荐阅读