0

有谁知道在 NSString 或相同字符的 NSArray 中查找字符的速度更有效?

我想知道哪个算法有最好和最有效的算法来找到正确的值。

我实际上想在字母表中找到一个字符的位置。例如E在字母表中找到“”的位置@"ABCDE....XYZ"[NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",...,@"X",@"Y",@"Z"];

哪个是更好的搜索?NSString 还是 NSArray?

4

1 回答 1

3

如果只是 AZ:

NSString *string = @"A";
int position = (int)[string characterAtIndex:0]-64;
NSLog(@"%d", position);

只是出于好奇:

NSString *alphabetString = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSMutableArray *alphabetArray = [NSMutableArray array];
for(int pos = 0; pos < [alphabetString length]; pos++) {

    [alphabetArray addObject:[alphabetString substringWithRange:NSMakeRange(pos, 1)]];
}

NSString *check = @"A";

// check with rangeOfString
NSDate *start = [NSDate date];
for(int i = 0; i < 1000000; i++) {

    int position = [alphabetString rangeOfString:check].location + 1;
}
NSDate *end = [NSDate date];
NSLog(@"STRING | time needed: %f", [end timeIntervalSinceDate:start]);

// check with indexOfObject
start = [NSDate date];
for(int i = 0; i < 1000000; i++) {

    int position = [alphabetArray indexOfObject:check] + 1;
}
end = [NSDate date];
NSLog(@"ARRAY | time needed: %f", [end timeIntervalSinceDate:start]);

// check with ASCII position
start = [NSDate date];
for(int i = 0; i < 1000000; i++) {

    int position = (int)[check characterAtIndex:0]-64;
}
end = [NSDate date];
NSLog(@"ASCII | time needed: %f", [end timeIntervalSinceDate:start]);

安慰:

STRING | time needed: 0.156067
ARRAY | time needed: 0.213297
ASCII | time needed: 0.017055
于 2012-07-12T16:54:05.107 回答