ios obj C separate string into chars and add letters
How can I separate a string? For example, into开发者_如何学编程 e x a m p l e, and generate a summation sumatory with the defined value for each letter [ a=1, b =2, c=3,..z=26]
You can use characterAtIndex
to extract a specific character from your string, e.g.
[myString characterAtIndex:1]
Or loop through all:
for (int i=0; i < [myString length]; i++) {
... [myString characterAtIndex:i]
// You can then decide how to assign a value to each individual string, via a switch.
}
Here is a way to do so :
NSMutableArray *chars = [NSMutableArray arrayWithCapacity:26];
// fill the array
unsigned int i;
for(i = 0; i < 26; i++) {
NSString *s = [NSString stringWithFormat:@"%c", (i+65)];
[chars addObject:s];
}
// now you have [0:"a", 1:"b", ..., 25:"z"]
NSUInteger sum = 0;
NSString lowerCaseString = [myString lowerCaseString];
for (int i=0; i < [myString length]; i++) {
NSString *character = [lowerCaseString substringWithRange:NSMakeRange(i, 1)];
// edit thanks to mortenfast ;-)
NSUInteger pos = [chars indexOfObject:character];
if(pos != NSNotFound) {
sum += (pos+1);
}
}
A block version for iOS 4.0:
__block int sum = 0;
NSString *string = [NSString stringWithString:@"abcdefghijklmnopqrstuvwxyz"];
[string enumerateSubstringsInRange:NSMakeRange(0,[string length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
// 'a'=97=0x61=01100001, 'A'=65=0x41=01000001
// 26 letters and 2^5-1=31 so only 5 lower bits needed
sum += [substring characterAtIndex:0] & 0x1F;
// which is the same as
// sum += [substring characterAtIndex:0] -'a'+1;
}];
精彩评论