What is the more elegant way to remove all characters after specific character in the String object in Swift

后端 未结 4 769
既然无缘
既然无缘 2021-02-01 15:06

What is the more elegant way to remove all characters after specific character in the String object in Swift?

Suppose that I have the following string:

相关标签:
4条回答
  • 2021-02-01 15:21

    Here is a way to do it:

    var str = "str.str"
    
    if let dotRange = str.rangeOfString(".") {
        str.removeRange(dotRange.startIndex..<str.endIndex)
    }
    

    Update In Swift 3 it is:

    var str = "str.str"
    
    if let dotRange = str.range(of: ".") {
      str.removeSubrange(dotRange.lowerBound..<str.endIndex)
    }
    
    0 讨论(0)
  • 2021-02-01 15:28

    Swift 5.1

    0 讨论(0)
  • 2021-02-01 15:39

    I think this is better approach:

    Update with Swift 4: (substring is now deprecated)

    let smth = "element=value"
    
    if let index = (smth.range(of: "=")?.upperBound)
    {
      //prints "value"
      let afterEqualsTo = String(smth.suffix(from: index))
    
      //prints "element="
      let beforeEqualsToContainingSymbol = String(smth.prefix(upTo: index))
    }
    
    if let index = (smth.range(of: "=")?.lowerBound)
    {
      //prints "=value"
      let afterEqualsToContainingSymbol = String(smth.suffix(from: index))
    
      //prints "element"
      let beforeEqualsTo = String(smth.prefix(upTo: index))
    }
    
    0 讨论(0)
  • 2021-02-01 15:44

    Quite a compact way would be:

    var str = "str.str"
    str = str.componentsSeparatedByString(".")[0]
    

    Another option you might be interested in, which works for your example 'str.str' but doesn't fit your specification is:

    str = str.stringByDeletingPathExtension
    // Returns a new string made by deleting the extension (if any, and only the last)
    // from the `String`
    
    0 讨论(0)
提交回复
热议问题