ios - 如何在每 N 个单词后将子字符串作为分隔符添加到段落

标签 ios swift string

例如

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/

相关文章:

swift - 执行被中断,带有参数的 func 调用上的 EXC 错误指令 - Swift iOS

python - Python 中区分大小写的字符串替换

c# - 字典中的 ToString c#

ios - iOS9中如何调用NSObject类中的UIAlertviewController?

ios - NSDateFormatter 在 IOS10 中返回 nil

ios - 添加多个 ImageView 帧时对象的数量只有一个

ios - Swift 枚举值不可访问

ios - xcode - 如何提取由字符分隔的字符串的一部分“

ios - 无法在 iPhone 6 中安装我的 ARKit 支持的应用程序,但苹果的演示应用程序在同一部 iPhone 上成功运行

ios - 从 NSString 中删除所有非英文字符