Как добавить подстроку в качестве разделителя к абзацу после каждого N слов - PullRequest
0 голосов
/ 10 мая 2018

например

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"

Ответы [ 2 ]

0 голосов
/ 10 мая 2018

Я настраиваю хорошее решение для того, чтобы прочитать комментарии в 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))
0 голосов
/ 10 мая 2018

Вы преобразуете строку в массив, а затем используете 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...