簡體   English   中英

將數組排序到字典中

[英]Sort array into dictionary

我有很多字符串的數組。 我不想把它們排成字典,所以所有字符串都是從同一個字母開始進入一個數組然后數組成為一個鍵的值; 鍵將是其值的數組中的所有單詞開始的字母。

Key = "A" >> Value = "array = apple, animal, alphabet, abc ..."
Key = "B" >> Value = "array = bat, ball, banana ..."

我怎樣才能做到這一點? 非常感謝提前!

NSArray *list = [NSArray arrayWithObjects:@"apple, animal, bat, ball", nil];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *word in list) {
    NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
    NSMutableArray *letterList = [dict objectForKey:firstLetter];
    if (!letterList) {
        letterList = [NSMutableArray array];
        [dict setObject:letterList forKey:firstLetter];
    }
    [letterList addObject:word];
}
NSLog(@"%@", dict);

您可以通過以下步驟實現您的目標:

  1. 創建一個空但可變的字典。
  2. 獲得第一個角色。
  3. 如果該角色的密鑰不存在,請創建它。
  4. 將單詞添加到鍵的值(應該是NSMutableArray)。
  5. 對所有鍵重復步驟#2。

以下是這些步驟的Objective-C代碼。 請注意,我假設您希望密鑰不區分大小寫

// create our dummy dataset
NSArray * wordArray = [NSArray arrayWithObjects:@"Apple", 
                       @"Pickle", @"Monkey", @"Taco", 
                       @"arsenal", @"punch", @"twitch", 
                       @"mushy", nil];
// setup a dictionary
NSMutableDictionary * wordDictionary = [[NSMutableDictionary alloc] init];
for (NSString * word in wordArray) {
    // remove uppercaseString if you wish to keys case sensitive.
    NSString * letter = [[word substringWithRange:NSMakeRange(0, 1)] uppercaseString];
    NSMutableArray * array = [wordDictionary objectForKey:letter];
    if (!array) {
        // the key doesn't exist, so we will create it.
        [wordDictionary setObject:(array = [NSMutableArray array]) forKey:letter];
    }
    [array addObject:word];
}
NSLog(@"Word dictionary: %@", wordDictionary);

看一下這個主題,它們解決了幾乎和你一樣的問題 - 在目標中將NSArray過濾成新的NSArray-c讓我知道它是否有用,所以我會再為你編寫一個代碼示例。

使用它按字母順序對數組的內容進行排序,進一步設計符合要求

[keywordListArr sortUsingSelector:@selector(localizedCaseInsensitiveCompare :)];

我剛剛寫了這個樣本。 它看起來很簡單,可以滿足您的需求。

NSArray *names = [NSArray arrayWithObjects:@"Anna", @"Antony", @"Jack", @"John", @"Nikita", @"Mark", @"Matthew", nil];

NSString *alphabet = @"ABCDEFGHIJKLMNOPQRSTUWXYZ";
NSMutableDictionary *sortedNames = [NSMutableDictionary dictionary];

for(int characterIndex = 0; characterIndex < 25; characterIndex++) {
    NSString *alphabetCharacter = [alphabet substringWithRange:NSMakeRange(characterIndex, 1)];
    NSArray *filteredNames = [names filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF BEGINSWITH[C] %@", alphabetCharacter]];        
    [sortedNames setObject:filteredNames forKey:alphabetCharacter];
}

//Just for testing purposes let's take a look into our sorted data
for(NSString *key in sortedNames) {
    for(NSString *value in [sortedNames valueForKey:key]) {
        NSLog(@"%@:%@", key, value);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM