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

时间:2018-05-10 06:49:37

标签: 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."

我需要在每N个字后添加substring seperator "$$$$"

就像 for 3 words

 "Lorem Ipsum is $$$$ simply dummy text $$$$  of the printing $$$$ ....etc"

2 个答案:

答案 0 :(得分:3)

将字符串转换为数组,然后使用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)

答案 1 :(得分:0)

我为3条步骤中的阅读评论配置了良好的解决方案

extension String {
    func addSeperator(_ seperator:String ,after nWords : Int) -> String{
             // 1 •  create array of words
             let wordsArray = self.components(separatedBy: " ")

             // 2 • create squence for nwords using stride
            // Returns a sequence from a starting value to, but not including, an end value, stepping by the specified amount.
            let sequence =  stride(from: 0, to: wordsArray.count, by: nWords)

             //3 • now creat array of array [["",""],["",""]...etc]  and join each sub array by space " "
             // then join final array by your seperator and add space
          let splitValue = sequence.map({Array(wordsArray[$0..<min($0+nWords,wordsArray.count)]).joined(separator: " ")}).joined(separator: " \(seperator) ")

        return splitValue
    }
}


 print(paragraph.addSeperator("$$$", after: 2))