我想将行号添加到字符串中。
例如:
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
.
如何归档上述预期结果?
可以的
split
\n
enumerate
获取索引的数组map
每串以index+1
加:
加element
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
。