for循环遍历NSString字符串

  版本1:  

    NSString *hello = @"hello world";
    
    for (int i = 0 ; i < hello.length; i ++) {
        unichar charactor = [hello characterAtIndex:i];
        NSLog(@"%C",charactor);
    }

上面的方法在一些字符如😊😢等在字符串中时则不适用了 

 

改进版 :  rangeOfComposedCharacterSequenceAtIndex:能够获取到完整字的范围

NSString是utf-16编码(?不确定是不是),但有一部分字符需要用2个16位字符才能表示

    NSRange range;
    for (int i = 0; i < hello.length ; i += range.length ) {
        unichar chara = [hello characterAtIndex:i];
        range = [hello rangeOfComposedCharacterSequenceAtIndex:i];
        NSString *subStr = [hello substringWithRange:range];
        NSLog(@"%@ %@",subStr,NSStringFromRange(range));
    }

 

posted on 2014-09-09 18:23  永远的冰蝴蝶  阅读(3391)  评论(0编辑  收藏  举报

导航