julia - 如何遍历字符串中的行?
问题描述
我在 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
.
推荐阅读
- javascript - 用 JsPDF 替换 VirtualPrintEngine
- npm - NPM 配置文件在哪里?
- snakemake - Snakemake表格配置、展开、合并——如何正确展开输入文件?
- python - Python 打印我的类对象内存地址而不是我的数组的值
- php - 为什么事件监听器没有在 Lumen 中触发?
- arduino - 如果客户端重新连接,如何抑制 MQTT Last Will 消息?
- multithreading - 使用 Start-Process 时 Invoke-Parallel 正在等待
- google-analytics - 使用 hits.hitNumber 获取特定命中后发生的命中
- sql-server - 是否可以使用 T-SQL 从数据库创建部分 dacpac?
- types - 创建一个基本上是String,但与String不兼容的类型?