英文:
Use .replacingOccurrences with dynamic replacement value
问题
要向字符串添加行号,您可以尝试以下方法:
var counter = 0
content = content.split(separator: "\n", omittingEmptySubsequences: false).map { line in
counter += 1
return "\(counter):\(line)"
}.joined(separator: "\n")
这将给字符串添加行号,包括空行,得到您期望的结果:
content = "1:hello\n2:\n3:world"
这里使用了split函数将字符串拆分成行,然后使用map函数为每一行添加行号,最后使用joined函数将它们重新连接在一起。这样可以保留空行。
英文:
I want to add the line numbers to a String.
For example:
let content = "hello\n\nworld"
should result in
content = "1:hello\n2:\n3:world"
.replacingOccurrences does not allow replacing \n with a dynamic value, in my case an incremental number.
E.g.,
var counter = 0
content = "1: " content.replacingOccurrences(of: "\n", with: "getNumber(): $0")
__________________________
func getNumber() -> Int {
counter += 1
return counter
}
results in
1:hello\n1:\n1:world as getNumber is only called once by replacingOccurrences.
Splitting the String and then adding the line number is not a solution as it "eats" empty lines \n\n.
How can archive the above described expected result?
答案1
得分: 2
以下是代码的翻译部分:
你可以
1. 通过 `\n` 来拆分字符串
2. 使用 `enumerate` 函数来获取索引
3. 将每个字符串映射为 `index+1` 加上 `:` 再加上元素本身
4. 将数组合并回字符串
---
let content = "hello\n\nworld"
let result = content
.split(separator: "\n", omittingEmptySubsequences: false) // 或者 .components(separatedBy: "\n")
.enumerated()
.map {"\($0.0+1):\($0.1)"}
.joined(separator: "\n")
要去除空行,请将 `omittingEmptySubsequences` 设置为 `true`。
英文:
You can
splitthe string by\nenumeratethe array to get also the indicesmapeach string toindex+1plus:plus theelementjointhe array back to a string
let content = "hello\n\nworld"
let result = content
.split(separator: "\n", omittingEmptySubsequences: false) // or .components(separatedBy: "\n")
.enumerated()
.map {"\($0.0+1):\($0.1)"}
.joined(separator: "\n")
To get rid of empty lines set omittingEmptySubsequences to true.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论