【问题标题】:How to iterate over the lines in a string?如何遍历字符串中的行?
【发布时间】:2020-11-02 15:12:09
【问题描述】:

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

【问题讨论】:

  • 还要注意split返回一个SubString而不是String的向量。所以分配并没有那么多。
  • @JunTian 谢谢,很高兴知道。我没有遇到SubString

标签: julia


【解决方案1】:

您可以为此使用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,正如 cmets 中所指出的那样。 split 基本上是对字符串的索引,并且不会为每一行分配新的Strings,而不是eachline

【讨论】:

  • 请注意,split 会更快,因为它分配的数量更少。
猜你喜欢
  • 2011-05-13
  • 2011-03-04
  • 2012-09-12
  • 2010-10-10
  • 1970-01-01
  • 1970-01-01
  • 2018-11-19
  • 1970-01-01
相关资源
最近更新 更多