- 想到截取字符串首先想到的是OC的截取字符串的subString方法,所以自然聯(lián)想到swift是否也提供相應(yīng)的API锐帜,結(jié)果還真有相應(yīng)的方法咆贬,但是需要傳遞的參數(shù)是什么呢肄满?
1,String類(lèi)型提供的截取字符串的方法
str.substring(with: Range)
str.substring(to: String.Index)
str.substring(from: String.Index)
2搬葬,我們發(fā)現(xiàn)參數(shù)都和String.Index有關(guān)那么String.Index是什么類(lèi)型呢荷腊?
- 因?yàn)镾tring類(lèi)型是基于UNicode標(biāo)量建立的, 所以不同的字符可能占用不同數(shù)量的內(nèi)存空間(最明顯的例子就是emoji字符占用兩個(gè))急凰。所以如果要查找字符串中指定“位置”的字符就要從頭開(kāi)始依次計(jì)算當(dāng)前字符所占空間大小,然后找下一個(gè)字符。所以我們不能再像OC那樣使用整數(shù)類(lèi)型的索引String為我們提供了其特有的索引類(lèi)型String.Index還提供了相應(yīng)的計(jì)算索引的方法
print(str2)
print(str2[str2.startIndex])
//注意String的endIndex不能作為訪問(wèn)其中字符的下標(biāo)因?yàn)閑ndIndex始終指向最后一個(gè)字符后面
print(str2[str2.index(before: str2.endIndex)])
print(str2[str2.index(after: str2.startIndex)])
print(str2[str2.index(str2.startIndex, offsetBy: 2)])
3抡锈,知道了String.Index那么Range<String.Index>就是字符串索引類(lèi)型的范圍用...或者..<來(lái)表示
// 截取子字符串
var str = "hello, world! telephone =12345"
let startIndex = str.startIndex
let endIndex = str.index(str.endIndex, offsetBy: -5)
let range = startIndex..<endIndex // 注意 這里不能包含endIndex 不然會(huì)報(bào)錯(cuò) Cannot convert value of type 'ClosedRange<String.Index>' to expected argument type 'Range<String.Index>'
let subStr = str.substring(with: range)
print(subStr)
4,注意點(diǎn)
截取字符串的時(shí)候創(chuàng)建范圍的時(shí)候如果使用...會(huì)報(bào)錯(cuò)Cannot convert value of type 'ClosedRange'to expected argument type 'Range'意思就是傳入閉的范圍要使用..<來(lái)表示范圍
對(duì)于一個(gè)字符串的Range不能用于截取另外一個(gè)字符串因?yàn)閮蓚€(gè)字符串的存儲(chǔ)結(jié)構(gòu)不一樣