Jem
Jem

Reputation: 6406

ObjC string/char manipulation + parsing

The following piece of code is supposed to return two integers: val1 = 2 and val2 = 5.

    NSString *col = @"1245DD";

    char c1 = [col characterAtIndex:1];
    char c2 = [col characterAtIndex:3];

    int val1 = [[[NSString alloc] initWithUTF8String:&c1] intValue];
    int val2 = [[[NSString alloc] initWithUTF8String:&c2] intValue];

inspecting values at runtime:

good so far.

But then:

I don't understand why val2 always ends up being the concatenation of c2 and c1. What am I missing? thanks,

Upvotes: 1

Views: 364

Answers (1)

trojanfoe
trojanfoe

Reputation: 122401

You are creating an NSString object as a UTF-8 string, that is in fact a single character. You need to NUL-terminate the UTF-8 string if you want to use it like this.

Note that [NSString characterAtIndex:] returns a unichar, not a char, so use [NSString initWithCharacters:length:] instead where you can tell the method how many characters to use:

NSString col = @"1245DD";

unichar c1 = [col characterAtIndex:1];
unichar c2 = [col characterAtIndex:3];

int val1 = [[[NSString alloc] initWithCharacters:&c1 length:1] intValue];
int val2 = [[[NSString alloc] initWithCharacters:&c2 length:1] intValue];

Upvotes: 3

Related Questions