简体   繁体   中英

Convert NSString to unicode with escape

NSString *string1 = @"\u03C0";
NSLog(@"string1: %@", string1);  // result of a Pi symbol

NSString *string2 = @"03C0";
NSString *string3 = [@"\\u" stringByAppendingString:string2];
NSLog(@"string3: %@", string3);  // result of \u03C0 but need it to be a Pi symbol as well

I would think string3 would give the same result as string1. But It does not. Any idea how to fix this?

When you type in a string literal with \香 , this is treated as a special character literal by the compiler. The compiler will convert that syntax directly to the resulting character.

Your string3 is being handled at runtime. The \香 syntax has no special meaning at runtime.

You can do this:

NSString *string2 = @"03C0";
NSScanner *scanner = [NSScanner scannerWithString:string2];
unsigned int code;
[scanner scanHexInt:&code];
NSString *string3 = [NSString stringWithFormat:@"%C", (unsigned short)code];
NSLog(@"string3: %@", string3);

If you know the code is then you can use it directly:

NSString *string3 = [NSString stringWithFormat:@"%C", (unsigned short)0x03C0];
NSLog(@"string3: %@", string3);

Better yet, type it in directly:

NSString *string3 = @"π";
NSLog(@"string3: %@", string3);

The answer lies in your question.

You say this as UNICODE Character \π, not as UNICODE string.

Therefore as you use stringByAppendingString: it returns a string to string3 , not the character.

is one single Unicode character, ie just another representation for the pi character. A string of the characters '\\','u', etc. is a different thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM