使用具有动态替换值的 .replacingOccurrences

问题描述 投票:0回答:1

我想将行号添加到字符串中。
例如:

let content = "hello\n\nworld"

应该导致
content = "1:hello\n2:\n3:world"

.replacingOccurrences 不允许用动态值替换

\n
,在我的例子中是增量数字。
例如,

var counter = 0
content = "1: " content.replacingOccurrences(of: "\n", with: "getNumber(): $0")
__________________________

func getNumber() -> Int {
        counter += 1
        return counter
}

结果

1:hello\n1:\n1:world
因为
getNumber
只被
replacingOccurrences
调用一次。
拆分字符串然后添加行号不是解决方案,因为它“吃掉”了空行
\n\n
.

如何归档上述预期结果?

swift
1个回答
1
投票

可以的

  1. split
    \n
  2. 的字符串
  3. enumerate
    获取索引的数组
  4. map
    每串以
    index+1
    :
    element
  5. join
    数组变回字符串

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")

要摆脱空行,请将

omittingEmptySubsequences
设置为
true

© www.soinside.com 2019 - 2024. All rights reserved.