【问题标题】:Replace sequence of spaces in string with a single character in swift用swift中的单个字符替换字符串中的空格序列
【发布时间】:2016-04-01 18:28:58
【问题描述】:

我想用下划线替换字符串中的一系列空格。例如

"This       is     a string with a lot of spaces!"

应该变成

"This_is_a_string_with_a_lot_of_spaces!"

如何做到这一点?

【问题讨论】:

    标签: string swift replace


    【解决方案1】:

    替代的非正则表达式解决方案:

    let foo = "This       is     a string with a lot of spaces!"
    let bar = foo
        .componentsSeparatedByString(" ")
        .filter { !$0.isEmpty }
        .joinWithSeparator("_")
    
    print(bar) /* This_is_a_string_with_a_lot_of_spaces! */
    

    也适用于 unicode 字符(感谢@MartinR 提供了这个漂亮的示例)

    let foo = "?? ??   ? ?? ? ?"
    
    // ...
    
    /* ??_??_?_??_?_? */
    

    【讨论】:

    • 过滤器的使用非常巧妙。
    • @NateBirkholz 但是,我应该指出,上面的这种方法不会分别替换第一个单词和最后一个单词之前和之后的空格组;这些空格将被删除(例如" This is a string with a lot of spaces! " 将产生与"This is a string with a lot of spaces!" 相同的结果)。
    • 这正是我所需要的,所以这不是问题
    【解决方案2】:

    @remus 的建议可以简化(并使 Unicode/Emoji/Flag-safe)为

    let myString = "  This       is     a string with a lot of spaces! ??    ??  ??  "
    let replacement = myString.stringByReplacingOccurrencesOfString("\\s+", withString: "_", options: .RegularExpressionSearch)
    print(replacement)
    // _This_is_a_string_with_a_lot_of_spaces!_??_??_??_
    

    【讨论】:

      【解决方案3】:

      您可以使用简单的正则表达式替换来做到这一点:

      let myString = "?? ?? ? ?? ? ?"
      if let regex = try? NSRegularExpression(pattern: "\\s+", options: []) {
          let replacement = regex.stringByReplacingMatchesInString(myString, options: .WithTransparentBounds, range: NSMakeRange(0, (myString as NSString).length), withTemplate: "_")
          print(replacement)
          // "??_??_?_??_?_?"
      }
      

      【讨论】:

      • 使用let myString = "?? ?? ? ?? ? ?" 测试您的代码 ... :)
      • WHHHYYYYY UNICODE WHYYYY
      【解决方案4】:

      替代的非正则表达式,纯 Swift(没有桥接到NSString)解决方案:

      let spaced = "This       is     a string with a lot of spaces!"
      
      let under = spaced.characters.split(" ", allowEmptySlices: false).map(String.init).joinWithSeparator("_")
      

      转换时不删除前导和尾随空格的替代版本。为简洁起见,稍微混淆了... ;-)

      let reduced = String(spaced.characters.reduce([Character]()) { let n = $1 == " " ? "_" : $1; var o = $0; o.append(n); guard let e = $0.last else { return o }; return e == "_" && n == "_" ? $0 : o })
      

      可能有一个更聪明的解决方案涉及flatMap(),但我会把它留给比我更聪明的人!

      【讨论】:

      • 请注意,与@dfris 的解决方案一样,这将删除而不是替换初始和尾随空格。
      猜你喜欢
      • 2013-05-09
      • 1970-01-01
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 2015-03-19
      • 1970-01-01
      • 2018-12-01
      相关资源
      最近更新 更多