如何解决.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
相关产品推荐
相关产品推荐

