zerowords
zerowords

Reputation: 3113

extracting integer from nsstring

Debug log looks as follows.

2013-06-09 17:09:09.192 BridgeDeal[2430:11303] suito: 2K
2013-06-09 17:09:09.193 BridgeDeal[2430:11303] suit: 50
2013-06-09 17:09:09.193 BridgeDeal[2430:11303] suito: 2Q
2013-06-09 17:09:09.193 BridgeDeal[2430:11303] suit: 50
2013-06-09 17:09:09.194 BridgeDeal[2430:11303] suito: 3J
2013-06-09 17:09:09.194 BridgeDeal[2430:11303] suit: 51

The values for suito above are correct, but not the values for suit above. Instead for the values of suit I am hoping to get 2,2,3 .

for (int i = 0; i<3; i++) {
    NSInteger suit = [[self.cardList objectAtIndex:i ] characterAtIndex:0] ;
    NSLog(@"suito: %@", [self.cardList objectAtIndex:i ]);
    NSLog(@"suit: %d", suit);

}

cardlist is declared as follows.

@property (nonatomic, weak) NSMutableArray *cardList;

I have tried the following code but get the error: bUnexpected type name 'NSRange'

NSInteger suit = [[self.cardList objectAtIndex:i ] substringWithRange:NSRange(0,1)]  ;

Upvotes: 0

Views: 167

Answers (2)

Alex Lew
Alex Lew

Reputation: 2124

Change NSLog(@"suit: %d",suit); to NSLog(@"suit: %d",suit - '0');.

When you call characterAtIndex on the NSString object, it returns a unichar (unsigned short) variable; you then store that value in an NSInteger. You'd think that would give you an error. The reason it doesn't is because unichar (and in C, char) variables are actually integers (in this case, unichar is just typedef'd an unsigned short). Each character ('a', 'b', 'c', 'd', etc.) has a different number associated with it. It so happens that the number associated with the character '2' in the ASCII character set is 50, and the number associated with '3' is 51. Since (in ASCII anyway) the characters for the digits '0' through '9' are all sequential, you can "hack" your way to get the actual number represented by subtracting the value for '0' from the value for your character (suit - '0'). Since the value for '0' (in ASCII) is 48, subtracting it will give you 2, 2, and 3 instead of 50, 50, and 51.

If you are representing card suits as numbers, you might consider storing them in the array itself as numbers instead of strings.

Upvotes: 1

Wain
Wain

Reputation: 119031

What you're getting is the ASCII code for the number. That's what the character is.

Your second section of code is better but use NSMakeRange or (NSRange){0,1}

Upvotes: 2

Related Questions