I assume that:
- You are reading this RTF data from a file or other external source.
- You are parsing it yourself (not using, say, AppKit's built-in RTF parser).
- You have a reason why you're parsing it yourself, and that reason isn't “wait, AppKit has this built in?”.
- You have come upon
\u…
in the input you're parsing and need to convert that to a character for further handling and/or inclusion in the output text.
- You have ruled out
\uc
, which is a different thing (it specifies the number of non-Unicode bytes that follow the \u…
sequence, if I understood the RTF spec correctly).
\u
is followed by hexadecimal digits. You need to parse those to a number; that number is the Unicode code point number for the character the sequence represents. You then need to create an NSString containing that character.
If you're using NSScanner to parse the input, then (assuming you have already scanned past the \u
itself) you can simply ask the scanner to scanHexInt:
. Pass a pointer to an unsigned int
variable.
If you're not using NSScanner, do whatever makes sense for however you're parsing it. For example, if you've converted the RTF data to a C string and are reading through it yourself, you'll want to use strtoul
to parse the hex number. It'll interpret the number in whatever base you specify (in this case, 16) and then put the pointer to the next character wherever you want it.
Your unsigned int
or unsigned long
variable will then contain the Unicode code point value for the specified character. In the example from your question, that will be 0x10003
, or U+10003.
Now, for most characters, you could simply assign that over to a unichar
variable and create an NSString from that. That won't work here: unichar
s only go up to 0xFFFF
, and this code point is higher than that (in technical terms, it's outside the Basic Multilingual Plane).
Fortunately, *CF*String has a function to help you:
unsigned int codePoint = /*…*/;
unichar characters[2];
NSUInteger numCharacters = 0;
if (CFStringGetSurrogatePairForLongCharacter(codePoint, characters)) {
numCharacters = 2;
} else {
characters[0] = codePoint;
numCharacters = 1;
}
You can then use stringWithCharacters:length:
to create an NSString from this array of 16-bit characters.