3

最初の文字が異なる場合にのみ、各文字列の最初の文字をキャプチャして新しい NSArray に入れる方法を知りたいです。

たとえば、次のような配列がある場合

"a, aaa, aaaa, b, c, d, dd, ddd"

新しい NSArray ではこのようになります

"a, b, c, d"

どんな助けでも大歓迎です。

4

4 に答える 4

9

このようなもの:

- (NSArray *)indexLettersForStrings:(NSArray *)strings {
    NSMutableArray *letters = [NSMutableArray array];
    NSString *currentLetter = nil;
    for (NSString *string in strings) {
        if (string.length > 0) {
            NSString *letter = [string substringToIndex:1];
            if (![letter isEqualToString:currentLetter]) {
                [letters addObject:letter];
                currentLetter = letter;
            }
        }
    }
    return [NSArray arrayWithArray:letters];
}
于 2012-11-06T22:06:00.103 に答える
2

NSString+LetterIndex.h

@interface NSString (LetterIndex)
@property (nonatomic, readonly) NSString * firstLetter;
@end

NSString+LetterIndex.m

@implementation NSString (LetterIndex)

- (NSString *)firstLetter
{
    return self.length ? [self substringToIndex:1] : @"";
}

あなたの方法:

- (NSArray *)indexLettersForStrings:(NSArray *)strings {
    NSSet * distinctValues = [NSSet setWithArray:[strings valueForKey:@"firstLetter"]];
    return [[distinctValues allObjects] sortedArrayUsingSelector:@selector(compare:)]
}

また、カスタム クラスのオブジェクトがいくつかあり、それらを文字列パラメーターの最初の文字でグループ化したい場合は、これを使用できます。

NSSet * distinctValues = [NSSet setWithArray:[objects valueForKeyPath:@"myStringParam.firstLetter"]];
于 2014-07-01T21:39:39.093 に答える
0
NSArray *array = [NSArray arrayWithObjects:@"a", @"aaa", @"aaaa",@"b", @"c", @"d", @"dd", @"ddd", nil];
BOOL control = YES;
NSMutableArray *array2 = [NSMutableArray array];
for (int i = 0; i<array.count; i++) {
    for (int j = 0; j<array2.count;j++){
        if ([[array2 objectAtIndex:j]isEqualToString:[[array objectAtIndex:i]substringToIndex:1]]){
            control = NO;
        }
        else
            control = YES;
    }
    if (control)
        [array2 addObject:[[array objectAtIndex:i]substringToIndex:1]];
}
于 2012-11-06T22:13:00.227 に答える
0

これを試して:

NSArray *arr = @[@"a", @"aaa", @"aaaa", @"b", @"c", @"d", @"dd", @"ddd"];
NSMutableArray *newArr = [NSMutableArray array];
NSMutableSet *set = [NSMutableSet set];

for (NSString *str in arr)
{
    if (![set containsObject:[str substringToIndex:1]])
        [newArr addObject:[str substringToIndex:1]];
    [set addObject:[str substringToIndex:1]];

}

NSLog(@"%@", newArr);

これは Set を使用して、過去にスローされた発生を追跡します。存在しない場合は、それらを新しい配列に配置します。

于 2012-11-06T22:14:19.807 に答える