8

我正在尝试按字母顺序重新排列单词。例如,tomato 会变成 amoott,或者 stack 会变​​成 ackst。

我已经找到了一些在 C 中使用 char 数组执行此操作的方法,但是我在使其在 NSString 对象的范围内工作时遇到了问题。

在 NSString 对象本身中有更简单的方法吗?

4

4 回答 4

12

您可以将字符串的每个字符存储到一个对象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
于 2012-11-13T11:06:57.537 回答
6

我认为将字符串分隔为字符串数组(数组中的每个字符串仅包含原始字符串中的一个字符)。然后对数组进行排序就OK了。这效率不高,但当字符串不是很长时就足够了。我已经测试了代码。

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:@""];
于 2012-11-13T11:43:08.077 回答
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);
于 2014-09-01T16:49:53.790 回答
0

只是另一个使用NSMutableString和的例子sortUsingComparator:

NSMutableString *mutableString = [[NSMutableString alloc] initWithString:@"tomat"];
[mutableString appendString:@"o"];
NSLog(@"Orignal string: %@", mutableString);

NSMutableArray *charArray = [NSMutableArray array];
for (int i = 0; i < mutableString.length; ++i) {
    [charArray addObject:[NSNumber numberWithChar:[mutableString characterAtIndex:i]]];
}

[charArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
    if ([obj1 charValue] < [obj2 charValue]) return NSOrderedAscending;
    return NSOrderedDescending;
}];

[mutableString setString:@""];
for (int i = 0; i < charArray.count; ++i) {
    [mutableString appendFormat:@"%c", [charArray[i] charValue]];
}

NSLog(@"Sorted string: %@", mutableString);

输出:

Orignal string: tomato
Sorted string: amoott
于 2020-05-01T01:40:11.680 回答