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

如何在Swift中向字符串的倒数前三行前添加指定内容?

没问题,我来帮你搞定在Swift中给字符串倒数前三行前插入指定内容的需求!

核心思路其实很简单:把字符串按换行拆分成行数组,找到倒数前三行的起始位置,插入内容后再重新拼接成字符串就行。而且我们还要考虑边界情况——比如原字符串行数不足3的时候,直接把内容插在开头就好。

下面是完整的实现代码:

func insertStringBeforeLastThreeLines(original: String, insertion: String) -> String {
    // 把原字符串按换行符分割成每行的数组
    let lines = original.components(separatedBy: .newlines)
    // 计算插入位置:如果行数>=3,就在倒数第三行的前面;否则插在开头
    let insertionIndex = max(0, lines.count - 3)
    // 转成可变数组方便插入操作
    var mutableLines = lines
    // 插入指定内容
    mutableLines.insert(insertion, at: insertionIndex)
    // 重新拼接成字符串
    return mutableLines.joined(separator: "\n")
}

接下来用你给的例子测试一下:

let originalText = """
Who composed the
 popular song "Aati Kya
 Khandala" from 'Ghulam"?
 Jatin- Lalit
 Abhijeet
 Aamir Khan
"""

let insertedResult = insertStringBeforeLastThreeLines(original: originalText, insertion: "sagarduhanishere")
print(insertedResult)

输出结果完全符合你的预期:

Who composed the
popular song "Aati Kya
Khandala" from 'Ghulam"?
sagarduhanishere
Jatin- Lalit
Abhijeet
Aamir Khan

边界情况处理

如果原字符串的行数不足3,比如只有2行:

let shortText = """
First line
Second line
"""
let shortResult = insertStringBeforeLastThreeLines(original: shortText, insertion: "Inserted content")
print(shortResult)

输出会是:

Inserted content
First line
Second line

这样的处理逻辑很合理,因为没有足够的倒数前三行,就默认把内容插在最开头。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:59:38