iOS開(kāi)發(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ù)量。因此在沒(méi)有獲取字符串的可擴(kuò)展的字符群的范圍時(shí)候,就不能計(jì)算出字符串的字符數(shù)量。如果您正在處理一個(gè)長(zhǎng)字符串,需要注意characters屬性必須遍歷全部的 Unicode 標(biāo)量,來(lái)確定字符串的字符數(shù)量

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

3.前面提到,不同的字符可能會(huì)占用不同數(shù)量的內(nèi)存空間,所以要知道Character的確定位置,就必須從String開(kāi)頭遍歷每一個(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.通過(guò)調(diào)用 String 的 index(before:)index(after:)方法,可以立即得到前面或后面的一個(gè)索引。您還可以通過(guò)調(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)")//打?。簊tarIndexCharacter: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)")//打?。篹ndIndexCharacter:!
        
        
        //獲取字符串 第二個(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])//打?。篒ndex(_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í)??!!}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容