如何快速在字符串的最后三行之前添加一个新单词,以便该字符串可以从此转换:
"Who composed the\n
popular song "Aati Kya\n
Khandala" from 'Ghulam"?\n
Jatin- Lalit\n
Abhijeet\n
Aamir Khan"
对此:
"Who composed the\n
popular song "Aati Kya\n
Khandala" from 'Ghulam"?\n
sagarduhanishere\n
Jatin- Lalit\n
Abhijeet\n
Aamir Khan"
答案 0 :(得分:3)
我想你有这样的字符串
let string = """
"Who composed the
popular song "Aati Kya
Khandala" from 'Ghulam"?
Jatin- Lalit
Abhijeet
Aamir Khan"
"""
或类似的
let string = """
"Who composed the\npopular song "Aati Kya\nKhandala" from 'Ghulam"?\nJatin- Lalit\nAbhijeet\nAamir Khan"
"""
因此,首先将您的字符串分隔为字符串数组
var separated = string.components(separatedBy: "\n")
然后在需要的索引处插入新字符串
separated.insert("sagarduhanishere", at: separated.endIndex - 3)
然后将这个数组重新连接回一个字符串
let joined = separated.joined(separator: "\n")
var separated = string.components(separatedBy: "\n")
separated.insert("sagarduhanishere", at: separated.endIndex - 3)
let joined = separated.joined(separator: "\n")
print(joined)
"Who composed the popular song "Aati Kya Khandala" from 'Ghulam"? sagarduhanishere Jatin- Lalit Abhijeet Aamir Khan"
答案 1 :(得分:2)
可接受的答案适用于短字符串。为了获得更好的空间(和时间)复杂度,您可以避免不必要地分割字符串并重新结合数组的所有元素,方法是:
让我们从此文本开始:
let text = """
Who composed the
popular song "Aati Kya
Khandala" from 'Ghulam"?
Jatin- Lalit
Abhijeet
Aamir Khan
"""
结果将存储在此变量中:
var result = ""
使用代码belo,我们从原始字符串的末尾开始寻找第三个\n
:
let start = text.startIndex
let end = text.endIndex
var index = text.index(end, offsetBy: -1)
var linesToGo = 3
while start < index {
if text[index] == "\n" {
linesToGo -= 1
}
if linesToGo == 0 {
index = text.index(index, offsetBy: 1)
result = text[start..<index] + "sagarduhanishere\n" + text[index..<end]
break
}
index = text.index(index, offsetBy: -1)
}
然后我们可以检查是否找到3行
if linesToGo != 0 {
fatalError("More lines needed")
}
然后打印结果或在代码中使用它:
print(result)
输出:
Who composed the popular song "Aati Kya Khandala" from 'Ghulam"? sagarduhanishere Jatin- Lalit Abhijeet Aamir Khan
答案 2 :(得分:2)
这是Regex方式。这是另一种选择。
<section id="langues" class="container-fluid bg-dark">
<article class="col-12 my-3"> <br>
<h2 class="text-white">Langues</h2>
<hr class="blanche">
<div class="row">
<div class="col-2"> <img src="./00_sources/icons/SVG/en.svg" alt="english" height="48px" width="48px" /> </div>
<div class="col-10">
<p class="text-white text-left ">Lu, écrit et parlé (professionnel)</p>
</div>
<div class="col-2"> <img src="./00_sources/icons/SVG/ar.svg" alt="arabic" height="48px" width="48px" /> </div>
<div class="col-10">
<p class="text-white text-left">Langue maternelle</p>
</div>
<div class="col-2"> <img src="./00_sources/icons/SVG/ber.svg" alt="berbere" height="48px" width="48px" /> </div>
<div class="col-10">
<p class="text-white text-left">Langue maternelle</p>
</div>
<div class="col-2"> <img src="./00_sources/icons/SVG/es.svg" alt="espanol" height="48px" width="48px" /> </div>
<div class="col-10">
<p class="text-white text-left">Scolaire</p>
</div>
</div>
</article>