Swift String剪切

let str = "helloworld"
let index3 = str.index(str.startIndex, offsetBy: 3)
let index4 = str.index(str.startIndex, offsetBy: 6)
let sub4 = str[index3..

字符串查找举例

      let firstReturnMoneyTimeTemp:String? = "2019年8月"
                                        // 找到“年”所在range
                                        let yearRange = firstReturnMoneyTimeTemp?.range(of: "年")
                            /*
   /// Returns the distance between two indices.
    ///
    /// - Parameters:
    ///   - start: A valid index of the collection.
    ///   - end: Another valid index of the collection. If `end` is equal to
    ///     `start`, the result is zero.
    /// - Returns: The distance between `start` and `end`.
    ///
    /// - Complexity: O(*n*), where *n* is the resulting distance.
*/
                                        let yearDistance = (firstReturnMoneyTimeTemp?.distance(from: firstReturnMoneyTimeTemp!.startIndex, to: yearRange!.lowerBound))!
                                        // 比如 2019
                                        let firstReturnMoneyYear = firstReturnMoneyTimeTemp?.prefix(yearDistance)
                                        
                                        let firstReturnMoneyYearVaule:Int = Int(String(firstReturnMoneyYear!))!
                                        
                                        // 找到“月”所在range
                                        let monthRange = firstReturnMoneyTimeTemp?.range(of: "月")
// 返回从 upperBound 到 lowerBound(不包含)位置之间的字符
                            let firstReturnMonth = firstReturnMoneyTimeTemp![yearRange!.upperBound ..< monthRange!.lowerBound]
                            

你可能感兴趣的:(Swift String剪切)