NSString to treat “regular english alphabets” and

2019-01-25 23:34发布

There is a textView in which I can enter Characters. characters can be a,b,c,d etc or a smiley face added using emoji keyboard.

-(void)textFieldDidEndEditing:(UITextField *)textField{
    NSLog(@"len:%lu",textField.length);
    NSLog(@"char:%c",[textField.text characterAtIndex:0]);
}

Currently , The above function gives following outputs

if textField.text = @"qq"
len:2
char:q

if textField.text = @"                

2条回答
贪生不怕死
2楼-- · 2019-01-26 00:02

Since Apple screwed up emoji (actually Unicode planes above 0) this becomes difficult. It seems it is necessary to enumerate through the composed character to get the actual length.

Note: The NSString method length does not return the number of characters but the number of code units (not characters) in unichars. See NSString and Unicode - Strings - objc.io issue #9.

Example code:

NSString *text = @"qqq                                                                    
查看更多
ら.Afraid
3楼-- · 2019-01-26 00:04

This is what i did to cut a string with emoji characters

+(NSUInteger)unicodeLength:(NSString*)string{
    return [string lengthOfBytesUsingEncoding:NSUTF32StringEncoding]/4;
}

+(NSString*)unicodeString:(NSString*)string toLenght:(NSUInteger)len{

    if (len >= string.length){
        return string;
    }

    NSInteger charposition = 0;
    for (int i = 0; i < len; i++){
        NSInteger remainingChars = string.length-charposition;
        if (remainingChars >= 2){
            NSString* s = [string substringWithRange:NSMakeRange(charposition,2)];
            if ([self unicodeLength:s] == 1){
                charposition++;
            }
        }
        charposition++;
    }
    return [string substringToIndex:charposition];
}
查看更多
登录 后发表回答