swift3.0-string.index转int的方法

代码如下,通过截取string.index中的字符,来获得对应的int,

    ///计算range
    ///originString : 原始字符串
    ///calculString :  要获取下标的字符
    ///返回值: calculString在originString中的下标,元组类型,包含起始下标和结束下标
    func calculRange(withString originString: String, calculString: String)-> (start: Int, end: Int) {
        let range = originString.range(of: calculString)
        if range == nil {
            print("originString中不包含calculString")
            return (0,0)
        }
        let rangeStr = String(describing: range?.lowerBound)
        let positionRange1 = rangeStr.range(of: "_position: ")
        let positionRange2 = rangeStr.range(of: ")")
        let str = rangeStr.substring(with: ((positionRange1?.upperBound)!..<(positionRange2?.lowerBound)!))
        
        let rangeStr2 = String.init(describing: range?.upperBound)
        print(rangeStr2)
        let positionRange3 = rangeStr2.range(of: "_position: ")
        let positionRange4 = rangeStr2.range(of: ")")
        let str2 = rangeStr2.substring(with: ((positionRange3?.upperBound)!..<(positionRange4?.lowerBound)!))
        print(str2)
        let result = (start: Int(str)!, end: Int(str2)!)
        return result 
    }

  • 调用
        let originString = "周末闲着无聊,想起最近遇到一个关于文字显示设置的小问题,想着以后可能还会经常用到,所以趁这个时候一起整理一下,方便以后备用"
        let result = calculRange(withString: originString, calculString: "无聊")
        print(result)
  • 打印结果
(4, 6)

你可能感兴趣的:(swift3.0-string.index转int的方法)