【问题标题】:Replace between substrings in swift?快速替换子字符串?
【发布时间】:2019-06-04 18:22:20
【问题描述】:

我有一个这样的字符串:

let someString = "The (randomcharacters)(someknowncharacters) are playing in the NBA Finals"

我想用字符串Warriors 替换字符串The(some 之间的所有内容。我已经研究过使用 replacingOcurrences 但这并没有达到我想要的效果。

【问题讨论】:

  • 这个问题现在有点不清楚,你想替换的总是“猛龙”还是那部分也是随机的?我假设 (somerandom...) 之前有一个空格?
  • 这是您在运行时获得的字符串,即您不能只对字符串进行插值吗?
  • @JoakimDanielson 没有空间。我想取代的并不总是“猛龙队”。我想要做的是能够在两个已知的字符串之间进行替换。
  • 那么“somerandomcharacters”真的不是随机的吗?我认为您需要给出一些示例并解释它们应该如何更改以及编译时已知的内容以及运行时已知的内容。

标签: swift string replace


【解决方案1】:

这是另一个使用replaceOccurencesOf的尝试

func replace(_ original: String, between firstPart: String, and secondPart: String, with: String ) -> String {
    let pattern = "\(firstPart) .* \(secondPart)"
    let replacement = "\(firstPart) \(with) \(secondPart)"
    return original.replacingOccurrences(of: pattern, with: replacement, options: .regularExpression)
}

它可能需要在处理替换单词周围的空间方面进行一些调整。

例子

let newString = replace("The Raptors are playing in the NBA Finals", between: "The", and: "are", with: "Warriors")

【讨论】:

    【解决方案2】:

    使用一些“somerandomcharacters”意味着您实际上是在使用字符串作为(非常糟糕的)工具来传输多条数据。但我们已经有办法做到这一点,使用数据类型。

    我们可以创建一个结构来保存描述篮球比赛的必要信息。我们可以在整个应用程序中传递这些数据,并且可以非常轻松地访问其重要组件。只有我们的 UI 层需要一个字符串,所以我们只在最后一刻生成这个结构的字符串描述,就在 UI 层。

    struct BasketballTeam {
        var name: String
    }
    
    struct BasketballGame: CustomStringConvertible {
        let homeTeam: BasketballTeam
        let awayTeam: BasketballTeam
        let eventName: String
    
        var description: String {
            return "The \(homeTeam.name) are playing the \(awayTeam.name) in the \(eventName)."
        }
    }
    
    let game = BasketballGame(
        homeTeam: BasketballTeam(name: "Toronto Raptors"),
        awayTeam: BasketballTeam(name: "Golden State Warriors"),
        eventName: "NBA Finals"
    )
    print(game.description) // => The Toronto Raptors are playing the Golden State Warriors in the NBA Finals.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-29
      • 2017-07-18
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 2016-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多