How can I escape unicode characters in a NSString?

孤人 提交于 2019-11-29 07:22:39

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;  
}
NSDictionary *someDict = [ NSDictionary dictionaryWithObjectsAndKeys: 
    someString, @"thestring" ];

Don't forget the nil sentinel. ;)

The console output looks like this:

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

with the string's unicode character escaped.

They're all Unicode characters.

Is there any method to convert a NSString to this escaped representation?

That's the dictionary (or some private method of NSPropertyListSerialization or private function of CFPropertyList) doing that, not the string. The \U sequence in that output is part of the OpenStep plist format. If you output the plist as XML using NSPropertyListSerialization, you'll find the ü (currently) encoded as naked UTF-8.

As far as I know, there is no built-in method, public or private, that will do the same escaping for you on a string alone. The closest thing is the strvis function, but that works byte-by-byte; it doesn't understand Unicode or UTFs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!