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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM