Ios “要处理的字符串”;普通英文字母;还有表情符号或日语之类的字符

Ios “要处理的字符串”;普通英文字母;还有表情符号或日语之类的字符,ios,unicode,nsstring,unicode-string,Ios,Unicode,Nsstring,Unicode String,有一个文本视图,我可以在其中输入字符。字符可以是a、b、c、d等,也可以是使用表情键盘添加的笑脸 -(void)textFieldDidEndEditing:(UITextField *)textField{ NSLog(@"len:%lu",textField.length); NSLog(@"char:%c",[textField.text characterAtIndex:0]); } 目前,上述功能提供以下输出 if textField.text = @"qq" len

有一个文本视图,我可以在其中输入字符。字符可以是a、b、c、d等,也可以是使用表情键盘添加的笑脸

-(void)textFieldDidEndEditing:(UITextField *)textField{
    NSLog(@"len:%lu",textField.length);
    NSLog(@"char:%c",[textField.text characterAtIndex:0]);
}
目前,上述功能提供以下输出

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

if textField.text = @"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 = @"qqqThis 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];
}
如果textField.text=@“qq”
蓝:2
char:q

如果textField.text=@“,因为苹果搞错了表情符号(实际上Unicode平面大于0),这就变得很困难。似乎有必要枚举合成字符以获得实际长度

注意:
NSString
方法
length
不返回字符数,而是返回unichars中的代码单位(非字符)数。请参阅

示例代码:


NSString*text=@“qqq这就是我用表情符号剪切字符串的方法

+(NSUInteger)Unicode长度:(NSString*)字符串{
返回[string lengthofBytes使用编码:NSUTF32StringEncoding]/4;
}
+(NSString*)unicodeString:(NSString*)字符串长度:(NSUTEGER)len{
if(len>=string.length){
返回字符串;
}
NSInteger charposition=0;
对于(int i=0;i=2){
NSString*s=[字符串substringWithRange:NSMakeRange(charposition,2)];
如果([self-unicodeLength:s]==1){
charposition++;
}
}
charposition++;
}
返回[string substringToIndex:charposition];
}

你想做什么?问题是什么?@Zaph:问题是我必须只在文本字段中粘贴字符串的前4个字符,这4个字符可以是“qqqq”或“好的,苹果搞砸了,textField.text.length返回unichars的数量。请看我的新答案。谢谢-我能够使用
[string LengthofBytes SusingEncoding:NSUTF32StringEncoding]/4
。如何在适当的索引处获取字符?如果我的输入字符串为@“QQQ”,则不能假设NSString的工作方式。这也是错误的,“您的解决方案看起来很不错。谢谢!请同时查看其他方法。我为起初不理解此问题而道歉,我甚至阅读了objc.io文章,但没有连接。请参阅所选答案。更好的解决方案!