Swift : How to get the string before a certain character?

前端 未结 11 1887
北恋
北恋 2020-12-24 01:45

How do I get the string before a certain character in swift? The code below is how I did it in Objective C, but can\'t seem to perform the same task in Swift. Any tips or su

11条回答
  •  不思量自难忘°
    2020-12-24 02:36

    Below is kind of a whole combo

    let string = "This a string split using * and this is left."
    if let range = string.range(of: "*") {
        let lastPartIncludingDelimiter = string.substring(from: range.lowerBound)
        print(lastPartIncludingDelimiter) // print * and this is left.
    
        let lastPartExcludingDelimiter = string.substring(from: range.upperBound)
        print(lastPartExcludingDelimiter) // print and this is left.
    
        let firstPartIncludingDelimiter = string.substring(to: range.upperBound)
        print(firstPartIncludingDelimiter) // print This a string split using *
    
        let firstPartExcludingDelimiter = string.substring(to: range.lowerBound)
        print(firstPartExcludingDelimiter) // print This a string split using
    }
    

提交回复
热议问题