2012-11-13 252 views
6

我試圖按字母順序重新排列單詞。例如,西紅柿會變得肥胖,或者堆疊會變得很糟糕。按字母順序對NSString中的字符進行排序

我發現了一些用char數組在C中做這個的方法,但是我有問題讓它在NSString對象的範圍內工作。

在NSString對象本身中有更簡單的方法嗎?

回答

4

我想單獨將字符串轉換爲字符串數組(數組中的每個字符串只包含來自原始字符串的一個字符)。然後對數組進行排序即可。這並不高效,但當字符串不是很長時就足夠了。我測試了代碼。

NSString *str = @"stack"; 
NSMutableArray *charArray = [NSMutableArray arrayWithCapacity:str.length]; 
for (int i=0; i<str.length; ++i) { 
    NSString *charStr = [str substringWithRange:NSMakeRange(i, 1)]; 
    [charArray addObject:charStr]; 
} 

NSString *sortedStr = [[charArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] componentsJoinedByString:@""]; 
+1

方法名稱應該是sortedArrayUsingComparator而不是sortUsingComparator – tiguero

+1

注意,使用'substringWithRange:'喜歡這意味着這個過程不會與像'O'字符組成的工作。這不是一個致命的異議,只是一個警告。 –

10

您可以將每個字符串的字符存儲到NSArrayNSNumber對象中,然後對其進行排序。似乎有點貴,所以我可能只是用qsort()來代替。

在這裏它作爲一個Objective-C類(未測試):

的NSString + SortExtension.h:

#import <Foundation/Foundation.h> 

@interface NSString (SortExtension) 
- (NSString *)sorted; 
@end 

的NSString + SortExtension.m:

#import "NSString+SortExtension.h" 

@implementation NSString (SortExtension) 

- (NSString *)sorted 
{ 
    // init 
    NSUInteger length = [self length]; 
    unichar *chars = (unichar *)malloc(sizeof(unichar) * length); 

    // extract 
    [self getCharacters:chars range:NSMakeRange(0, length)]; 

    // sort (for western alphabets only) 
    qsort_b(chars, length, sizeof(unichar), ^(const void *l, const void *r) { 
     unichar left = *(unichar *)l; 
     unichar right = *(unichar *)r; 
     return (int)(left - right); 
    }); 

    // recreate 
    NSString *sorted = [NSString stringWithCharacters:chars length:length]; 

    // clean-up 
    free(chars); 

    return sorted; 
} 

@end 
2
// --------- Function To Make an Array from String 
NSArray *makeArrayFromString(NSString *my_string) { 
    NSMutableArray *array = [[NSMutableArray alloc] init]; 
    for (int i = 0; i < my_string.length; i ++) { 
     [array addObject:[NSString stringWithFormat:@"%c", [my_string characterAtIndex:i]]]; 
    } 
    return array; 

} 

// --------- Function To Sort Array 
NSArray *sortArrayAlphabetically(NSArray *my_array) { 
    my_array= [my_array sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 
    return my_array; 
} 

// --------- Function Combine Array To Single String 
NSString *combineArrayIntoString(NSArray *my_array) { 
    NSString * combinedString = [[my_array valueForKey:@"description"] componentsJoinedByString:@""]; 
    return combinedString; 
} 




// Now you can call the functions as in below where string_to_arrange is your string 
    NSArray *blowUpArray; 
    blowUpArray = makeArrayFromString(string_to_arrange); 
    blowUpArray = sortArrayAlphabetically(blowUpArray); 
    NSString *arrayToString= combineArrayIntoString(blowUpArray); 
    NSLog(@"arranged string = %@",arrayToString);