如何遍历字符串中的行?

DVN*_*old 5 julia

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

pfi*_*seb 10

您可以eachline为此使用:

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

julia> for line in eachline(IOBuffer(str))
         println(line)
       end
a
b
c
Run Code Online (Sandbox Code Playgroud)

还有一个直接对文件进行操作的版本,以防万一与您相关:

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");
Run Code Online (Sandbox Code Playgroud)

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

  • 请注意,“split”会更快,因为它进行的分配数量较少。 (2认同)