gpt4 book ai didi

julia - 如何遍历字符串中的行?

转载 作者:行者123 更新时间:2023-12-03 15:41:50 25 4
gpt4 key购买 nike

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

最佳答案

您可以使用 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 .

关于julia - 如何遍历字符串中的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64648161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com