iOS開發(fā) - 「Swift 學(xué)習(xí)」String索引、遍歷

Swift — String的索引佑吝、遍歷

\color{#FF0000}{提供五種String的遍歷方法:}

一、基于EnumeratedSequence的遍歷

//字符串的遍歷
        let randomString = "hello everybody"
        
        //基于EnumeratedSequence的遍歷
        for (i, char) in randomString.enumerated() {
            print("The results of the ergodic\(i): \(char)")
            /*打印輸出:
            The results of the ergodic0: h
            The results of the ergodic1: e
            The results of the ergodic2: l
            The results of the ergodic3: l
            The results of the ergodic4: o
            The results of the ergodic5:
            The results of the ergodic6: e
            The results of the ergodic7: v
            The results of the ergodic8: e
            The results of the ergodic9: r
            The results of the ergodic10: y
            The results of the ergodic11: b
            The results of the ergodic12: o
            The results of the ergodic13: d
            The results of the ergodic14: y
            */

二绳匀、for in 正序遍歷

//正序
        let randomString = "hello everybody"
        for char in randomString{
            print("The results of the ergodic:\(char)")
            /*打印輸出:
             The results of the ergodic:h
             The results of the ergodic:e
             The results of the ergodic:l
             The results of the ergodic:l
             The results of the ergodic:o
             The results of the ergodic:
             The results of the ergodic:e
             The results of the ergodic:v
             The results of the ergodic:e
             The results of the ergodic:r
             The results of the ergodic:y
             The results of the ergodic:b
             The results of the ergodic:o
             The results of the ergodic:d
             The results of the ergodic:y*/
        }

三芋忿、for in 逆序遍歷

//逆序
        let randomString = "hello everybody"
        var index = randomString.count
        for char in randomString.reversed() {
            index -= 1
            print("The results of the ergodic:\(index)=\(char)")
            /*打印輸出:
            The results of the ergodic:14=y
            The results of the ergodic:13=d
            The results of the ergodic:12=o
            The results of the ergodic:11=b
            The results of the ergodic:10=y
            The results of the ergodic:9=r
            The results of the ergodic:8=e
            The results of the ergodic:7=v
            The results of the ergodic:6=e
            The results of the ergodic:5=
            The results of the ergodic:4=o
            The results of the ergodic:3=l
            The results of the ergodic:2=l
            The results of the ergodic:1=e
            The results of the ergodic:0=h
            */
        }

字符串索引

在講解String基于索引的遍歷前先擴(kuò)展一下 字符串的索引,那么在提到字符串的索引前就要先認(rèn)識(shí)一下 \color{red}{“可擴(kuò)展的字形群集”}

字形群集

1.可擴(kuò)展的字符群集可以組成一個(gè)或者多個(gè) Unicode 標(biāo)量疾棵。這意味著不同的字符以及相同字符的不同表示方式可能需要不同數(shù)量的內(nèi)存空間來(lái)存儲(chǔ)戈钢。所以 Swift 中的字符在一個(gè)字符串中并不一定占用相同的內(nèi)存空間數(shù)量。因此在沒有獲取字符串的可擴(kuò)展的字符群的范圍時(shí)候是尔,就不能計(jì)算出字符串的字符數(shù)量殉了。如果您正在處理一個(gè)長(zhǎng)字符串,需要注意characters屬性必須遍歷全部的 Unicode 標(biāo)量拟枚,來(lái)確定字符串的字符數(shù)量薪铜。

2.另外需要注意的是通過characters屬性返回的字符數(shù)量并不總是與包含相同字符的NSString的length屬性相同。NSString的length屬性是利用 UTF-16 表示的十六位代碼單元數(shù)字恩溅,而不是 Unicode 可擴(kuò)展的字符群集隔箍。

3.前面提到,不同的字符可能會(huì)占用不同數(shù)量的內(nèi)存空間暴匠,所以要知道Character的確定位置鞍恢,就必須從String開頭遍歷每一個(gè) Unicode 標(biāo)量直到結(jié)尾傻粘。因此每窖,Swift 的字符串不能用整數(shù)(integer)做索引

如下的字符:

        //字符串字面量的特殊字符
        let dollarSign = "\u{24}"             // $, Unicode 標(biāo)量 U+0024
        let blackHeart = "\u{2665}"           // ?, Unicode 標(biāo)量 U+2665
        let sparklingHeart = "\u{1F496}"      // ??, Unicode 標(biāo)量 U+1F496
        
        print(dollarSign,blackHeart,sparklingHeart)//打印 $ ? ??
        
        //可擴(kuò)展的字形群集
        let eAcute: Character = "\u{E9}"                         // é
        let combinedEAcute: Character = "\u{65}\u{301}"          // e 后面加上  ?
        // eAcute 是 é, combinedEAcute 是 é
        print("eAcuteValue:\(eAcute),combinedEAcuteValue:\(combinedEAcute)")//打印 eAcuteValue:é,combinedEAcuteValue:é

索引

1.使用startIndex屬性可以獲取一個(gè)String的第一個(gè)Character的索引弦悉。使用endIndex屬性可以獲取最后一個(gè)Character的后一個(gè)位置的索引窒典。因此,endIndex屬性不能作為一個(gè)字符串的有效下標(biāo)稽莉。如果String是空串瀑志,startIndex和endIndex是相等的

2.通過調(diào)用 String 的 index(before:)index(after:)方法污秆,可以立即得到前面或后面的一個(gè)索引劈猪。您還可以通過調(diào)用 index(_:offsetBy:) 方法來(lái)獲取對(duì)應(yīng)偏移量的索引,這種方式可以避免多次調(diào)用 index(before:) 或 index(after:) 方法良拼。

       let stringIndexStr = "hello word!"
        
        //獲取字符串第一個(gè)索引的 字符
        let starIndexC = stringIndexStr[stringIndexStr.startIndex]//獲取字符串第一個(gè)索引的 字符
        print("startIndexValue:\(stringIndexStr.startIndex)")//打诱降谩: startIndexValue:Index(_base: Swift.String.UnicodeScalarView.Index(_position: 0), _countUTF16: 1)
 
        print("starIndexCharacter:\(starIndexC)")//打印:starIndexCharacter:h
        
        //獲取字符串最后一個(gè)索引的 字符
        //錯(cuò)誤方法
        //endIndex屬性不能作為一個(gè)字符串的有效下標(biāo),運(yùn)行時(shí)會(huì)崩潰
        //let endIndexC = stringIndexStr[stringIndexStr.endIndex]//試圖獲取越界索引對(duì)應(yīng)的 Character庸推,將引發(fā)一個(gè)運(yùn)行時(shí)錯(cuò)誤常侦。
        //print("endIndexCharacter:\(endIndexC)")
        
        //正確方法
        let endIndexC = stringIndexStr[stringIndexStr.index(before: stringIndexStr.endIndex)]//試圖獲取越界索引對(duì)應(yīng)的 Character浇冰,將引發(fā)一個(gè)運(yùn)行時(shí)錯(cuò)誤。
        print("endIndexCharacter:\(endIndexC)")//打恿觥:endIndexCharacter:!
        
        
        //獲取字符串 第二個(gè)索引的字符(第一個(gè)索引后面的一個(gè)索引值)
        let afterIndexC = stringIndexStr[stringIndexStr.index(after: stringIndexStr.startIndex)]//獲取字符串 第二個(gè)索引的字符(第一個(gè)索引后面的一個(gè)索引值)
        print(afterIndexC)//打又庀啊:e
        
        //獲取字符串末尾的一個(gè)字符
        let beforeIndexC = stringIndexStr[stringIndexStr.index(before: stringIndexStr.endIndex)]//獲取字符串末尾的一個(gè)字符(最后一個(gè)索引前面的一個(gè)索引,使用endIndex屬性可以獲取最后一個(gè)Character的后一個(gè)位置的索引坡倔,endIndex屬性不能作為一個(gè)字符串的有效下標(biāo))
        print("獲取字符串末尾的一個(gè)字符:\(beforeIndexC)")//打悠濉:獲取字符串末尾的一個(gè)字符: !
        
        
        //第一個(gè)索引4個(gè)偏移量之后的一個(gè)索引
        let offSetByIndex = stringIndexStr.index(stringIndexStr.startIndex, offsetBy: 4)//第一個(gè)索引4個(gè)偏移量之后的一個(gè)索引
        print(offSetByIndex,stringIndexStr[offSetByIndex])//打幼锼:Index(_base: Swift.String.UnicodeScalarView.Index(_position: 4), _countUTF16: 1) o

基于索引的遍歷

四仅仆、基于索引的正序遍歷

//基于索引的正序遍歷
        let randomString = "hello everybody"
        for i in 0..<randomString.count {
            let char: Character = randomString[randomString.index(randomString.startIndex, offsetBy: i)]
            print("swift-string ergodic\(i): \(char)")
            /*打印輸出:
            swift-string ergodic0: h
            swift-string ergodic1: e
            swift-string ergodic2: l
            swift-string ergodic3: l
            swift-string ergodic4: o
            swift-string ergodic5:
            swift-string ergodic6: e
            swift-string ergodic7: v
            swift-string ergodic8: e
            swift-string ergodic9: r
            swift-string ergodic10: y
            swift-string ergodic11: b
            swift-string ergodic12: o
            swift-string ergodic13: d
            swift-string ergodic14: y
            */
        }

五、基于索引的逆序遍歷

//基于索引的逆序遍歷
        let randomString = "hello everybody"
        for i in stride(from: randomString.count - 1, through: 0, by: -1) {
            let char: Character = randomString[randomString.index(randomString.startIndex, offsetBy: i)]
            print("swift-string ergodic\(i): \(char)")
            /*打印輸出:
             swift-string ergodic14: y
             swift-string ergodic13: d
             swift-string ergodic12: o
             swift-string ergodic11: b
             swift-string ergodic10: y
             swift-string ergodic9: r
             swift-string ergodic8: e
             swift-string ergodic7: v
             swift-string ergodic6: e
             swift-string ergodic5:
             swift-string ergodic4: o
             swift-string ergodic3: l
             swift-string ergodic2: l
             swift-string ergodic1: e
             swift-string ergodic0: h
             */
        }

以上五種Swift中String的遍歷方法總有一款用得到

\color{gray}{歡迎大佬兒來(lái)指正糾錯(cuò)垢袱,共同學(xué)習(xí)??D拱荨!}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末请契,一起剝皮案震驚了整個(gè)濱河市咳榜,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌爽锥,老刑警劉巖涌韩,帶你破解...
    沈念sama閱讀 218,755評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異氯夷,居然都是意外死亡臣樱,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門腮考,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)雇毫,“玉大人,你說我怎么就攤上這事踩蔚∨锓牛” “怎么了?”我有些...
    開封第一講書人閱讀 165,138評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵馅闽,是天一觀的道長(zhǎng)飘蚯。 經(jīng)常有香客問我,道長(zhǎng)福也,這世上最難降的妖魔是什么局骤? 我笑而不...
    開封第一講書人閱讀 58,791評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮暴凑,結(jié)果婚禮上峦甩,老公的妹妹穿的比我還像新娘。我一直安慰自己搬设,他們只是感情好穴店,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評(píng)論 6 392
  • 文/花漫 我一把揭開白布撕捍。 她就那樣靜靜地躺著,像睡著了一般泣洞。 火紅的嫁衣襯著肌膚如雪忧风。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,631評(píng)論 1 305
  • 那天球凰,我揣著相機(jī)與錄音狮腿,去河邊找鬼。 笑死呕诉,一個(gè)胖子當(dāng)著我的面吹牛缘厢,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播甩挫,決...
    沈念sama閱讀 40,362評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼贴硫,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了伊者?” 一聲冷哼從身側(cè)響起英遭,我...
    開封第一講書人閱讀 39,264評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎亦渗,沒想到半個(gè)月后挖诸,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡法精,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年多律,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片搂蜓。...
    茶點(diǎn)故事閱讀 40,040評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡狼荞,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出洛勉,到底是詐尸還是另有隱情粘秆,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評(píng)論 5 346
  • 正文 年R本政府宣布收毫,位于F島的核電站,受9級(jí)特大地震影響殷勘,放射性物質(zhì)發(fā)生泄漏此再。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評(píng)論 3 330
  • 文/蒙蒙 一玲销、第九天 我趴在偏房一處隱蔽的房頂上張望输拇。 院中可真熱鬧,春花似錦贤斜、人聲如沸策吠。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)猴抹。三九已至带族,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蟀给,已是汗流浹背蝙砌。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留跋理,地道東北人择克。 一個(gè)月前我還...
    沈念sama閱讀 48,247評(píng)論 3 371
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像前普,于是被迫代替她去往敵國(guó)和親肚邢。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容