You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决.replacingOccurrences动态替换失效的字符串行号添加问题?

解决字符串添加递增行号并保留空行的问题

直接用split(omittingEmptySubsequences: false)把字符串按换行符拆分成包含空元素的数组,这样就能保留所有空行对应的条目,接着遍历数组给每个元素加上递增的行号,最后再用换行符拼接起来即可。

示例代码(基础遍历版)

let content = "hello\n\nworld"
let lines = content.split(separator: "\n", omittingEmptySubsequences: false)
var numberedContent = ""

for (index, line) in lines.enumerated() {
    let lineNumber = index + 1
    numberedContent += "\(lineNumber):\(line)"
    if index != lines.count - 1 {
        numberedContent += "\n"
    }
}

print(numberedContent)
// 输出结果:
// 1:hello
// 2:
// 3:world

示例代码(简洁链式调用版)

let content = "hello\n\nworld"
let numberedContent = content
    .split(separator: "\n", omittingEmptySubsequences: false)
    .enumerated()
    .map { "\($0.offset + 1):\($0.element)" }
    .joined(separator: "\n")

原方法问题说明

  • 使用replacingOccurrences(of:with:)时,替换字符串会被预先求值一次,所以getNumber()只会执行一次,导致所有行号重复。
  • 拆分字符串时如果不加omittingEmptySubsequences: false参数,split会自动忽略空元素,从而丢失空行对应的行号条目。

内容的提问来源于stack exchange,提问作者Elektronenhirn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 22:43:20