Challenge 1 - solution

Hi guys!

This is the solution I came up with. I think this challenge can also be resolved using the NSString methods ‘substringFromIndex’ and ‘substringToIndex’.

If somebody thinks this solution can be improved ot there may be an alternative way, please!!! make it known.
Thanks :slight_smile:


#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        NSString *listOfNames = @"AMBER,john,Alex,CHris,ANdrew";
        
        /* 'name' is what I'm looking for */
        NSString *name = @"ALEX";
        
        /* rangeOfString:options: is the NSString method I use for a case-insensitive search (option: NSCaseInsensitiveSearch) */
        /* rangeOfString returns an NSRange (typedef struct) with two members: NSUInteger location & NSUInteger length */
        
        /* NSUInteger 'location' --> position of NSString *name's first character in the NSString *listOfNames */
        /* NSUInteger 'length' --> length of the NSString *name we are looking for */
        /* NSUInteger 'location' and NSUInteger 'length' provide the range we want --> [location, location + (length - 1)] */
        
        NSRange match = [listOfNames rangeOfString:name options: NSCaseInsensitiveSearch];
        
        
        if(match.location == NSNotFound) {
            NSLog(@"No match found\n");
        }else {
            NSLog(@"Match found\n");
            NSLog(@"%lu\n", match.location);
            NSLog(@"%lu\n", match.length);
            NSLog(@"[%lu, %lu]\n\n", match.location, match.location + match.location + (match.length - 1));
            
            /* substringWithRange: is the NSString method I use to return the portion of string I'm looking for */
            /* it takes as parameter an NSRange and calculates the range in the way explained above */
            
            NSString *searchedName = [listOfNames substringWithRange: match];
            NSLog(@"The portion of string is --> %@\n", searchedName);
            
        }
    }
    return 0;
}