我不知道我的解決方案是否是最好的方法,但它可以暫時解決您的問題:)。
1)首先,我寫了一個函數來獲取字符串中的@字符之前的數字,然後我實現了簡單的SELECTION SORT算法來使用這個函數對數組進行排序。
- (NSString*)getSubStringForString:(NSString*)value {
// First we will cut the frame_ string
NSMutableString *trimmedString = [NSMutableString stringWithString:[value substringWithRange:NSMakeRange(6, [value length]-6)]];
// New String to contain the numbers
NSMutableString *newString = [[NSMutableString alloc] init];
for (int i = 0; i < [trimmedString length] ; i++) {
NSString *singleChar = [trimmedString substringWithRange:NSMakeRange(i, 1)];
if (![singleChar isEqualToString:@"@"]) {
[newString appendString:singleChar];
} else {
break;
}
}
return newString;
}
這是選擇實現算法的排序。主要邏輯在for循環中。您可以將代碼複製到viewDidLoad方法中進行測試。
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"[email protected]",@"[email protected]",
@"[email protected]", @"[email protected]",
nil];
NSLog(@"Values before Sort: %@", array);
int iPos;
int iMin;
for (iPos = 0; iPos < [array count]; iPos++)
{
iMin = iPos;
for (int i = iPos+1; i < [array count]; i++)
{
if ([[self getSubStringForString:[array objectAtIndex:i]] intValue] >
[[self getSubStringForString:[array objectAtIndex:iMin]] intValue]) {
iMin = i;
}
}
if (iMin != iPos)
{
NSString *tempValue = [array objectAtIndex:iPos];
[array replaceObjectAtIndex:iPos withObject:[array objectAtIndex:iMin]];
[array replaceObjectAtIndex:iMin withObject:tempValue];
}
}
NSLog(@"Sorted Values: %@", array);
我希望它至少能讓你繼續。 :)
有關字母數字排序的正確答案,請參閱本G回答這裏http://stackoverflow.com/questions/1351182/how-to-sort-a-nsarray-alphabetically – 2017-02-28 02:46:08