Unreality
Unreality

Reputation: 4212

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

In Objective-C, how to get the Ascii Integer value of the first letter of a NSString?

Upvotes: 4

Views: 6013

Answers (2)

taskinoor
taskinoor

Reputation: 46027

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.

Upvotes: 3

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

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.

Upvotes: 8

Related Questions