Reputation: 89
NSString * str = @"ABCDEFGHILMN";
NSDictionary *dictOdd = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithInt:0], @"A",
[NSNumber numberWithInt:1], @"B",
[NSNumber numberWithInt:2], @"C",
[NSNumber numberWithInt:3], @"D",
...............................
nil];
NSDictionary *dictEven = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithInt:1], @"A",
[NSNumber numberWithInt:0], @"B",
[NSNumber numberWithInt:5], @"C",
[NSNumber numberWithInt:7], @"D",
...............................
nil];
int sum = 0;
for (int i=1; i < [str length]; i++){
if(i % 2){
sum += [dictPair objectForKey:str[i]];
}else{
sum += [dictEven objectForKey:str[i]];
}
}
I have created 2 dictionary for storage int numbers / letters, each letter have a int value.
I would make the sum of int numbers in relation to my str value, but i don't know how assign objectForKey:str[i]];
Upvotes: 0
Views: 301
Reputation: 6325
I think you are looking for characterAtIndex:
which would leave you with
sum+=[[dictPair objectForKey:[NSString stringWithFormat:@"%C",[str characterAtIndex:i]]] intValue];
Upvotes: 1
Reputation: 1623
You should do something like this, according to NSString Class Reference
Remember that NSNumber and int are different and you should convert before adding them.
NSString *str = ...
NSDictionary *dictOdd = ...
NSDictionary *dictOdd = ...
int sum = 0;
for (int i = 0; i < [str length]; i++) {
if(i % 2 == 0)
sum += [[dictPair objectForKey:[str characterAtIndex:i]] intValue];
else
sum += [[dictEven objectForKey:[str characterAtIndex:i]] intValue];
}
Upvotes: 0