关于IOS判断字符串长度的方法

 

 
    NSString *text=@"helloworld你好吗";//16
    NSUInteger length= text.length;
    NSUInteger length2=[text lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"length=%lu,length2=%lu,length3=%lu",(unsigned long)length ,(unsigned long)length2,[self unicodeLengthOfString:text]);

-(NSUInteger) unicodeLengthOfString: (NSString *) text {
    NSUInteger asciiLength = 0;
    for (NSUInteger i = 0; i < text.length; i++) {
        unichar uc = [text characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    NSUInteger unicodeLength = asciiLength / 2;
    if(asciiLength % 2) {
        unicodeLength++;
    }
    return asciiLength;
}

你可能感兴趣的:(iphone,ipad)