How can I escape unicode characters in a NSString?

前端 未结 2 1415
面向向阳花
面向向阳花 2020-12-18 04:50

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

NSString *someString = @\"Münster\";  
NSDictionary *som         


        
2条回答
  •  旧时难觅i
    2020-12-18 05:20

    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;  
    }
    

提交回复
热议问题