iOS开发 - 「Swift 学习」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基于索引的遍历前先扩展一下 字符串的索引,那么在提到字符串的索引前就要先认识一下 \color{red}{“可扩展的字形群集”}

字形群集

1.可扩展的字符群集可以组成一个或者多个 Unicode 标量。这意味着不同的字符以及相同字符的不同表示方式可能需要不同数量的内存空间来存储。所以 Swift 中的字符在一个字符串中并不一定占用相同的内存空间数量。因此在没有获取字符串的可扩展的字符群的范围时候,就不能计算出字符串的字符数量。如果您正在处理一个长字符串,需要注意characters属性必须遍历全部的 Unicode 标量,来确定字符串的字符数量

2.另外需要注意的是通过characters属性返回的字符数量并不总是与包含相同字符的NSString的length属性相同。NSString的length属性是利用 UTF-16 表示的十六位代码单元数字,而不是 Unicode 可扩展的字符群集

3.前面提到,不同的字符可能会占用不同数量的内存空间,所以要知道Character的确定位置,就必须从String开头遍历每一个 Unicode 标量直到结尾。因此,Swift 的字符串不能用整数(integer)做索引

如下的字符:

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

索引

1.使用startIndex属性可以获取一个String的第一个Character的索引。使用endIndex属性可以获取最后一个Character的后一个位置的索引。因此,endIndex属性不能作为一个字符串的有效下标如果String是空串,startIndex和endIndex是相等的

2.通过调用 String 的 index(before:)index(after:)方法,可以立即得到前面或后面的一个索引。您还可以通过调用 index(_:offsetBy:) 方法来获取对应偏移量的索引,这种方式可以避免多次调用 index(before:) 或 index(after:) 方法

       let stringIndexStr = "hello word!"
        
        //获取字符串第一个索引的 字符
        let starIndexC = stringIndexStr[stringIndexStr.startIndex]//获取字符串第一个索引的 字符
        print("startIndexValue:\(stringIndexStr.startIndex)")//打印: startIndexValue:Index(_base: Swift.String.UnicodeScalarView.Index(_position: 0), _countUTF16: 1)
 
        print("starIndexCharacter:\(starIndexC)")//打印:starIndexCharacter:h
        
        //获取字符串最后一个索引的 字符
        //错误方法
        //endIndex属性不能作为一个字符串的有效下标,运行时会崩溃
        //let endIndexC = stringIndexStr[stringIndexStr.endIndex]//试图获取越界索引对应的 Character,将引发一个运行时错误。
        //print("endIndexCharacter:\(endIndexC)")
        
        //正确方法
        let endIndexC = stringIndexStr[stringIndexStr.index(before: stringIndexStr.endIndex)]//试图获取越界索引对应的 Character,将引发一个运行时错误。
        print("endIndexCharacter:\(endIndexC)")//打印:endIndexCharacter:!
        
        
        //获取字符串 第二个索引的字符(第一个索引后面的一个索引值)
        let afterIndexC = stringIndexStr[stringIndexStr.index(after: stringIndexStr.startIndex)]//获取字符串 第二个索引的字符(第一个索引后面的一个索引值)
        print(afterIndexC)//打印:e
        
        //获取字符串末尾的一个字符
        let beforeIndexC = stringIndexStr[stringIndexStr.index(before: stringIndexStr.endIndex)]//获取字符串末尾的一个字符(最后一个索引前面的一个索引,使用endIndex属性可以获取最后一个Character的后一个位置的索引,endIndex属性不能作为一个字符串的有效下标)
        print("获取字符串末尾的一个字符:\(beforeIndexC)")//打印:获取字符串末尾的一个字符: !
        
        
        //第一个索引4个偏移量之后的一个索引
        let offSetByIndex = stringIndexStr.index(stringIndexStr.startIndex, offsetBy: 4)//第一个索引4个偏移量之后的一个索引
        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}{欢迎大佬儿来指正纠错,共同学习😏!!}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,135评论 6 514
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,317评论 3 397
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,596评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,481评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,492评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,153评论 1 309
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,737评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,657评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,193评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,276评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,420评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,093评论 5 349
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,783评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,262评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,390评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,787评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,427评论 2 359

推荐阅读更多精彩内容