【问题标题】:How to add substring as separator to paragraph after every N words如何在每 N 个单词之后将子字符串作为分隔符添加到段落
【发布时间】:2018-05-10 06:49:37
【问题描述】:

例如

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

变成这样三个字

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

【问题讨论】:

  • 我检查它并尝试为单词做
  • 你的?很好,我尝试了不同的方式,可能对你有帮助
  • 是的,我会在解决时继续工作,我会发布完整的解决方案
  • 我完成了任务,我应该上传我的答案

标签: ios swift string


【解决方案1】:

你把字符串转成数组,然后用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)

【讨论】:

  • 只需创建字符串扩展并发布它
  • 我认为这是一个最佳答案
【解决方案2】:

我为读取 cmets 配置了 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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 1970-01-01
    • 2023-03-05
    • 2019-10-29
    相关资源
    最近更新 更多