【问题标题】:How to split one long string of words into separate words in Swift?如何在 Swift 中将一长串单词拆分成单独的单词?
【发布时间】:2020-10-16 16:08:54
【问题描述】:

我正在解决这个问题,它有一串没有空格的单词。我要实现的就是在这个输入的单词之间加一个空格。这是我的代码:

func getOrder(_ input: String) -> String {

let menu = ["Pizza", "Milkshake", "Fries", "Onionrings", "Burger", "Coke", "Sandwich", "Chicken"]

    
return ""
}

getOrder("milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza")

【问题讨论】:

  • 你能有“garage”,比如初始字符串中“pizza”中的“he”吗?否则,快速完成它可能是:var toReturn = input; menu.forEach { toReturn = toReturn.replacingOccurrences(of: $0, with: " \($0) ", options: .caseInsensitive) }; return toReturn(它将用菜单中的值替换值(意味着以大写开头等)可以吗?
  • 是的。

标签: swift string


【解决方案1】:

这是一种方法,循环遍历菜单数组并用项目和空格替换每个找到的菜单项

func getOrder(_ input: String) -> String {
    
    let menu = ["Pizza", "Milkshake", "Fries", "Onionrings", "Burger", "Coke", "Sandwich", "Chicken"]
    
    var result = input
    menu.forEach { word in
        result = result.replacingOccurrences(of: word.lowercased(), with: "\(word) ")
    }
    
    return result.trimmingCharacters(in: .whitespaces)
}

【讨论】:

  • 我使用的是components,但这会删除我试图分离的单词。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
  • 2019-12-23
  • 2011-02-16
  • 1970-01-01
相关资源
最近更新 更多