如何在NSString中避免unicode字符? [英] How can I escape unicode characters in a NSString?

查看:147
本文介绍了如何在NSString中避免unicode字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pre $ NSString * someString = @ 明斯特;
NSDictionary * someDict = [NSDictionary dictionaryWithObjectsAndKeys:
someString,@thestring];
NSLog(@someDict:%@,[someDict description]);

控制台输出如下所示:

  unicode_test [3621:903] someDict:
{
thestring =M\U00fcnster;
}

与字符串的unicode字符转义。
是否有任何方法将NSString转换为此转义表示?

解决方案

可以使用循环来解决问题在给定字符串的UniChar字符串表示。实现为NSString的扩展,它看起来像这样:

   - (NSString *)escapedUnicode 
{
NSMutableString * uniString = [[NSMutableString alloc] init];
UniChar * uniBuffer =(UniChar *)malloc(sizeof(UniChar)* [self length]);
CFRange stringRange = CFRangeMake(0,[self length]);

CFStringGetCharacters((CFStringRef)self,stringRange,uniBuffer); (int i = 0; i< [self length]; i ++){
if(uniBuffer [i]> 0x7e)
[uniString appendFormat:@ \\u%04x,uniBuffer [i]];
else
[uniString appendFormat:@%c,uniBuffer [i]];
}

free(uniBuffer);

NSString * retString = [NSString stringWithString:uniString];
[uniString release];

return retString;
}


When I store a NSString inside some NSDictionary and log that dictionary to the console like this:

NSString *someString = @"Münster";  
NSDictionary *someDict = [ NSDictionary dictionaryWithObjectsAndKeys: 
    someString, @"thestring" ];
NSLog ( @"someDict: %@", [ someDict description ] );

The console output looks like this:

unicode_test[3621:903] someDict:
{
    thestring = "M\U00fcnster";
}

with the string's unicode character escaped. Is there any method to convert a NSString to this escaped representation?

解决方案

The problem could be solved using a loop on a UniChar-string representation of the given string. Implemented as extension on NSString it would look something like this:

- (NSString *) escapedUnicode  
{  
    NSMutableString *uniString = [ [ NSMutableString alloc ] init ];  
    UniChar *uniBuffer = (UniChar *) malloc ( sizeof(UniChar) * [ self length ] );  
    CFRange stringRange = CFRangeMake ( 0, [ self length ] );  

    CFStringGetCharacters ( (CFStringRef)self, stringRange, uniBuffer );  

    for ( int i = 0; i < [ self length ]; i++ ) {  
        if ( uniBuffer[i] > 0x7e )  
            [ uniString appendFormat: @"\\u%04x", uniBuffer[i] ];  
        else  
            [ uniString appendFormat: @"%c", uniBuffer[i] ];  
    }  

    free ( uniBuffer );  

    NSString *retString = [ NSString stringWithString: uniString ];  
    [ uniString release ];  

    return retString;  
}

这篇关于如何在NSString中避免unicode字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆