例如
let paragraph = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
我需要添加 substring seperator "$$$$"
在每 N 个单词之后
像这样3个词
"Lorem Ipsum is $$$$ simply dummy text $$$$ of the printing $$$$ ....etc"
最佳答案
你把字符串转成数组,然后用map加上分隔符:
extension String {
func add(separator: String, afterNWords: Int) -> String {
return split(separator: " ").enumerated().map { (index, element) in
index % afterNWords == afterNWords-1 ? "\(element) \(separator)" : String(element)
}.joined(separator: " ")
}
}
//Usage:
let result = paragraph.add(separator: "$$$$", afterNWords: 3)
关于ios - 如何在每 N 个单词后将子字符串作为分隔符添加到段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50267153/