Objective C : How to get the Ascii Integer value of the first letter of a NSString?

大兔子大兔子 提交于 2019-12-07 14:57:26

问题


Objective C : How to get the Ascii Integer value of the first letter of a NSString?


回答1:


if ([aString length] > 0) {
    unichar firstCharacter = [aString characterAtIndex: 0];
    // ...
}

That's all. unichar is an alias of unsigned short and so is an integer type. However, there is no guarantee the character is part of ASCII, as NSString is Unicode-based.




回答2:


unichar ch = [myString characterAtIndex:0]

Now as the name specified, it returns the unicode character value unichar which is actually a typedef of unsigned short. NSString is not ASCII string, but if the first character is really an ASCII character then you will get the correct ASCII value. And if the string is empty then this will raise an exception.




回答3:


If you really need to do it, turn the first character of the string into an NSData with ASCII encoding and then read it back.

There's some help in the String Programming Guide.



来源:https://stackoverflow.com/questions/4422385/objective-c-how-to-get-the-ascii-integer-value-of-the-first-letter-of-a-nsstri

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