代码之家  ›  专栏  ›  技术社区  ›  William Hu

swift如何拆分字符串但包含分隔符

  •  2
  • William Hu  · 技术社区  · 7 年前

    我有一根绳子 100 + 8 - 9 + 10 如何得到 ["100", "+", "8", "-", "9", "+", "10"] 数组中。

    let string = "100 + 8 - 9 + 10"
    let splitted = string.split(omittingEmptySubsequences: true, whereSeparator: { ["+", "-"].contains(String($0)) })
    

    但我得到了 ["100", "8", "9", "10"] 我迷路了 + - ,有什么好办法吗?谢谢!

    编辑 谢谢你的评论,不保证空间。可能是“100+8-9”。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Ashley Mills    7 年前

    如果不知道字符串是否包含空格,则可能应该使用 Scanner

    let string = "100 + 8 - 9 + 10"
    
    let removed = string.replacingOccurrences(of: " ", with: "")
    // "100+8-9+10"
    
    let scanner = Scanner(string: removed)
    
    let operators = CharacterSet(charactersIn: "+-*/")
    
    var components: [String] = []
    
    while !scanner.isAtEnd {
        var value: Int = 0
        if scanner.scanInt(&value) {
            components.append("\(value)")
        }
    
        var op: NSString? = ""
        if scanner.scanCharacters(from: operators, into: &op) {
            components.append(op! as String)
        }
    }
    
    print(components)
    
    // ["100", "+", "8", "-", "9", "+", "10"]
    
        2
  •  3
  •   Papershine    7 年前

    你可以用空格分开你的字符串。

    let splitted = string.split(separator: " ")
    

    价值 splitted

    ["100", "+", "8", "-", "9", "+", "10"]