最初の文字が異なる場合にのみ、各文字列の最初の文字をキャプチャして新しい NSArray に入れる方法を知りたいです。
たとえば、次のような配列がある場合
"a, aaa, aaaa, b, c, d, dd, ddd"
新しい NSArray ではこのようになります
"a, b, c, d"
どんな助けでも大歓迎です。
このようなもの:
- (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];
}
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"]];
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]];
}
これを試して:
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 を使用して、過去にスローされた発生を追跡します。存在しない場合は、それらを新しい配列に配置します。