美文网首页
swift字串符截取

swift字串符截取

作者: fishycx | 来源:发表于2019-09-26 11:51 被阅读0次

    ## 1.截取某字符串的前10个字符串

    let sub1 = str.prefix(10)

    ## 2.截取某字符串的后10个字符串

    let str1 = str.suffix(10)

    也可以换种写法

    let index2 = str.index(str.endIndex, offsetBy: -10)

    let sub4 = str[index2..

    ## 3.截取某字符串的第3个字符到第6个字符范围的字符串

    let index3 = str.index(str.startIndex, offsetBy:3)

    let index4 = str.index(str.startIndex, offsetBy:6)

    let sub4 = str[index3..

    ## 4.截取指定字符串

    截取 access_token开始以后的字符串

    ```

            if let range = urlStr.range(of:"access_token") {

                query =String(urlStr.suffix(from: range.lowerBound))

            }

    ```

    截取不包含 access_token开始以前的字符串

            if let range = urlStr.range(of:"access_token") {

                query =String(urlStr.suffix(from: range.lowerBound))

            }

      let testStr = "hello world"

        //这种方法和swift3.2 类似

    let index1 = testStr.index(testStr.endIndex, offsetBy: -5)

    let test1 = String(testStr.suffix(from: index1))

    //test1 = "hello"

    let index2 = testStr.index(testStr.startIndex, offsetBy: 5)

    let test2 = String(testStr.prefix(upTo: index2))//

    //test1 = "world"

    //当然你也可以这样,是不是更简洁了

    let test3 = String(testStr.suffix(5))

    //test3 = "hello"

    let test4 = String(testStr.prefix(5))

    相关文章

      网友评论

          本文标题:swift字串符截取

          本文链接:https://www.haomeiwen.com/subject/vjbguctx.html