Search code examples
objective-ccocoa-touchnsstringnsarray

Split an NSString into an array in Objective-C


How can I split the string @"Hello" to either:

  • a C array of 'H', 'e', 'l', 'l', 'o'

or:

  • an Objective-C array of @[@"H", @"e", @"l", @"l", @"o"]

Solution

  • If you're satisfied with a C array of chars, try:

    const char *array = [@"Hello" UTF8String];
    

    If you need an NSArray, try:

    NSMutableArray *array = [NSMutableArray array];
    NSString *str = @"Hello";
    for (int i = 0; i < [str length]; i++) {
        NSString *ch = [str substringWithRange:NSMakeRange(i, 1)];
        [array addObject:ch];
    }
    

    And array will contain each character as an element of it.