前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Swift3 获取String子字符串Substring简单扩展

Swift3 获取String子字符串Substring简单扩展

作者头像
韦弦zhy
发布2018-09-11 12:49:50
6120
发布2018-09-11 12:49:50
举报

Swift3更新后不兼容Swift2了,刚开始看Swift,发现好多方法都不能用了啊,那就只能自己摸索了,同时也在这与大家分享分享,正好让大家帮我指正。

在这里更新到Swift4了欢迎大家查阅、、、

1.新建一个字符串,是不是很机智(懒)

代码语言:javascript
复制
let str = "Do any additional setup after loading the view, typically from a nib."

2.测量字符串长度,因为Swift的String保函uicode字符串,以前的length不好使了,然后百度了好多方法例如: countElements(string),然而,然并软,并没有用,是下面的方法,()是插值,以后再也不用OC的那一大串了。。。

代码语言:javascript
复制
 print("string length: \(str.characters.count)")

3.获取第一个到第十个字符

代码语言:javascript
复制
let index1 = str.index(str.startIndex, offsetBy: 10)
let str1 = str.substring(to: index1)
print("string from 1 - 10 : \(str1)")
 //string from 1 - 10 : Do any add

4.获取倒数十个字符

代码语言:javascript
复制
let index2 = str.index(str.endIndex, offsetBy: -10)
let str2 = str.substring(from: index2)
print("string of last 10 : \(str2)")
 //string of last 10 : rom a nib.

5.获取自定义范围的字符串,比如4-6(any)

代码语言:javascript
复制
 let index3 = str.index(str.startIndex, offsetBy: 3) //为啥是3...因为...你懂得
 let index4 = str.index(str.startIndex, offsetBy: 6)
 let str3 = str.substring(with: index3..<index4)
 print("string from 4 - 6 : \(str3)") 
 //string from 4 - 6 : any

6.获取一个子字符串居然要那么长的三行代码?这怎么可以。。。立马就想到了分类啦,但是Swift中没有分类只有扩展,但anyway功能是一样的呀,我写了个简单的,大家将就着用哈

代码语言:javascript
复制
import Foundation
extension String {
    //获取子字符串
    func substingInRange(r: Range<Int>) -> String {
        let startIndex = self.index(self.startIndex, offsetBy:r.lowerBound)
        let endIndex   = self.index(self.startIndex, offsetBy:r.upperBound)
        return self.substring(with:startIndex..<endIndex)
    }
}

嗯,下面是用法

代码语言:javascript
复制
let str4 = str.substingInRange(r: 3..<6)
print("string from 4 - 6 : \(str4)") 
 //string from 4 - 6 : any

7.其他很多方法都和OC类似,比如hasPrefix(),hasSuffix(),uppercaseString,lowercaseString之类的,就先写到这里啦,在每天的下班后的有限的学习时间中发现了好玩的有时间就分享给大家,希望大家一起学习~

8.修改了下扩展,加在这里

代码语言:javascript
复制
import Foundation
extension String {
    //获取子字符串
    func substingInRange(r: Range<Int>) -> String? {
        if r.lowerBound < 0 || r.upperBound > self.characters.count{
            return nil
        }
        let startIndex = self.index(self.startIndex, offsetBy:r.lowerBound)
        let endIndex   = self.index(self.startIndex, offsetBy:r.upperBound)
        return self.substring(with:startIndex..<endIndex)
    }
}

//使用
if let str5 = str.substingInRange(r: 3..<6) {哦·
      print("string from 4 - 6 : \(str5)")
} else {
     print("range error")
}
//string from 4 - 6 : any

if let str6 = str.substingInRange(r: 3..<80) {
      print("string from 4 - 80 : \(str6)")
} else {
     print("range error")
}
//range erro
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.04.17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档