Get Unicode point of NSString and put that into another NSString

老子叫甜甜 提交于 2019-12-07 10:29:17

问题


What's the easiest way to get the Unicode value from an NSString? For example,

NSString *str = "A";
NSString *hex;

Now, I want to set the value of hex to the Unicode value of str (i.e. 0041)... How would I go about doing that?


回答1:


The unichar type is defined to be a 16-bit unicode value (eg, as indirectly documented in the description of the %C specifier), and you can get a unichar from a given position in an NSString using characterAtIndex:, or use getCharacters:range: if you want to fill a C array of unichars from the NSString more quickly than by querying them one by one.

NSUTF32StringEncoding is also a valid string encoding, as are a couple of endian-specific variants, in case you want to be absolutely future proof. You'd get a C array of those using the much more longwinded getBytes:maxLength:usedLength:encoding:options:range:remainingRange:.

EDIT: so, e.g.

NSString *str = @"A";

NSLog(@"16-bit unicode values are:");
for(int index = 0; index < [str length]; index++)
    NSLog(@"%04x", [str characterAtIndex:index]);



回答2:


You can use

NSData * u = [str dataUsingEncoding:NSUnicodeStringEncoding];
NSString *hex = [u description];

You may replace NSUnicodeStringEncoding by NSUTF8StringEncoding, NSUTF16StringEncoding (the same as NSUnicodeStringEncoding) or NSUTF32StringEncoding, or many other values.

See here for more



来源:https://stackoverflow.com/questions/9829931/get-unicode-point-of-nsstring-and-put-that-into-another-nsstring

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