假设我array
elements
"am","john","rosa","freedom"
。我想compare
这些元素和结果将是word
和size of the longest word
。我正在使用objective C
。
答案 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
,因此可以从块内部更改它们。