1

for example

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."

i need to add substring seperator "$$$$" after each N words

to be like this for 3 word

 "Lorem Ipsum is $$$$ simply dummy text $$$$  of the printing $$$$ ....etc"
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35

2 Answers2

3

You convert the string to an array, and then use map to add the separator:

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)
davebcn87
  • 819
  • 7
  • 4
0

I configure good solution for that read comments in 3 steps

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))
Abdelahad Darwish
  • 5,969
  • 1
  • 17
  • 35