Home > DeveloperSection > Forums > How to get First Character from each string of an Array
zack mathews
zack mathews

Total Post:21

Points:147
Posted on    November-18-2015 4:57 AM

 iPhone iPhone  Ios  Objective C 
Ratings:


 1 Reply(s)
 209  View(s)
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.



Tarun Kumar

Total Post:210

Points:1614
Supported
Posted on    November-18-2015 10:18 PM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick