大家好我怎么能把一个字符串,即:例子,分成例子,然后用每个字母的定义值生成summation sumatory [a = 1,b = 2 ,c = 3,.. z = 26]
谢谢!
答案 0 :(得分:9)
您可以使用characterAtIndex
从字符串中提取特定字符,例如
[myString characterAtIndex:1]
或循环遍历所有:
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.
}
答案 1 :(得分:7)
这是一种方法:
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);
}
}
答案 2 :(得分:3)
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;
}];