for循环遍历NSString字符串

时间:2014-09-09 19:55:39   收藏:0   阅读:306

  版本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));
    }

 

原文:http://www.cnblogs.com/binglin92/p/3963152.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!