如何比较数组元素?

时间:2010-08-31 14:57:52

标签: iphone objective-c

假设我array elements "am","john","rosa","freedom"。我想compare这些元素和结果将是wordsize of the longest word。我正在使用objective C

3 个答案:

答案 0 :(得分:2)

没有“内置”方式执行此操作,但您可以使用NSArray的{​​{1}}并在sortedArrayUsingSelector:上创建一个类别以提供{{1方法。

NSString

现在,您可以使用lengthCompare:

按升序对字符串进行排序
// NSString+LengthCompare.h
#import NSString.h
@interface NSString (LengthComparison)
- (NSComparisonResult)lengthCompare:(NSString *)aString;
@end

// NSString+LengthCompare.m
#import NSString+LengthCompare.h
@implememtation NSString (LengthComparison)
- (NSComparisonResult)lengthCompare:(NSString *)aString
{        
    if ([self length] < [aString length]) {
        return NSOrderedAscending;
    } else if ([self length] > [aString length]) {
        return NSOrderedDescending;
    } else {
        return NSOrderedSame;
    }
}
@end

答案 1 :(得分:0)

听起来像是一个经典的逻辑练习,还是我在你的问题中想念的东西?

int longestWordIndex = 0;
NSUInteger longestWordSize = 0;
for (int i=0 ; i<[nameArray count] ; i++) {
  NSString* element = (NSString*)[nameArray objectAtindex:i];
  if([element lenght] > longestWordSize) {
    longestWordSize = [element lenght];
    longestWordIndex = i;
  } 
}
NSLog("Longest word is %@ with size of :%d", [nameArray objectAtIndex:longestWordIndex], longestWordSize);

答案 2 :(得分:0)

我将为上面两个添加一个方法 - 使用一个块来完成迭代的主体。

__block NSUInteger longestWordSize = -1; // Make sure at least one object will be longer.
__block NSUInteger longestWordIndex;

[nameArray enumerateObjectsUsingBlock:^(id currentWord, NSUInteger index, BOOL *stop) {
    if ([currentWord length] > longestWordSize) {
        longestWordSize = [currentWord length];
        longestWordIndex = index;
    }
}];

NSLog("Longest word is %@ with size of :%d", [nameArray objectAtIndex:longestWordIndex], longestWordSize);

编辑:最大值和索引必须是存储类型__block,因此可以从块内部更改它们。