HOW TO GET FIRST CHARACTER FROM EACH STRING OF AN ARRAY

zack mathews

Total Post:23

Points:161
Posted by  zack mathews
 472  View(s)
Ratings:
Rate this:
I have an Array of String, I would like to know how to fetch the first character of each string when the first character is different to previous strings.
For example:
NSArray *arr = @[@"AA", @"AAA", @"B", @"BBB", @"BBBB", @"CC", @"DD"];
I want these character in another array:
A,B,C,D
Please help me.

  1. Tarun Kumar

    Post:214

    Points:1642
    Re: How to get First Character from each string of an Array

    For fetching and storing first character in an array use code like this:

    NSArray *stringArray = @[@"AA", @"AAA", @"B", @"BBB", @"BBBB", @"CC", @"DD"];
    NSMutableArray *fetchedArray = [NSMutableArray stringArray];
    NSMutableSet *mutableSet = [[NSMutableSet alloc]init];
    for (NSString *str in stringArray)
    {
        if(![mutableSet containsObject:[str substringToIndex:1]])
            [fetchedArray addObject:[str substringToIndex:1]];
        [mutableSet addObject:[str substringToIndex:1]];
    }
    NSLog(@"%@", fetchedArray);

    I hope the above code is helpful for you.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!