Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Create dictionary using array first letter

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 357
    Comment on it

    we often come to a situation where we have to create the dictionary based on the alphabetic order.

    So here is the program for creating a Dictionary with first letter of the array element. array element First letter is a key for adding the element in Dictionary

    #import "ViewController.h"
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
    
    NSMutableArray myDataArray=[[NSMutableArray alloc]initWithObjects:@"anane",@"bnane",@"cnane",@"anane1",@"bnane1",@"cnane1",@"anane2",@"bnane2",@"cnane2",@"anane3",@"bnane3",@"cnane3",@"anane4",@"bnane4",@"cnane5",@"anane6",@"bnane6",@"cnane6",@"madj",@"iuer",@"dkdk", nil];
    
     NSMutableDictionary dictForKeyAndValues= [NSMutableDictionary dictionary];
    
        for (NSString *word in myDataArray) {
            NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
    
            NSMutableArray *letterList = [dictForKeyAndValues objectForKey:firstLetter];
            if (!letterList) {
    
                NSLog(@"ye kab chalega");
                letterList = [NSMutableArray array];
                [dictForKeyAndValues setObject:letterList forKey:firstLetter];
            }
    
            [letterList addObject:word];
        }
        NSLog(@"%@", dictForKeyAndValues);
    }
    
    
    @end
    

    Output:

    {
        A =     (
            anane,
            anane1,
            anane2,
            anane3,
            anane4,
            anane6
        );
        B =     (
            bnane,
            bnane1,
            bnane2,
            bnane3,
            bnane4,
            bnane6
        );
        C =     (
            cnane,
            cnane1,
            cnane2,
            cnane3,
            cnane5,
            cnane6
        );
        D =     (
            dkdk
        );
        I =     (
            iuer
        );
        M =     (
            madj
        );
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: