Use .replacingOccurrences with dynamic replacement value

huangapple go评论65阅读模式
英文:

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

  1. split the string by \n
  2. enumerate the array to get also the indices
  3. map each string to index+1 plus : plus the element
  4. join the 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.

huangapple
  • 本文由 发表于 2023年3月3日 22:45:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75628516.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定