4

I'd like to convert NSString(ex. @"HELLO") to NSArray(ex. [@"H", @"E", @"L", @"L", @"O", nil]).

First, I tried to use componentsSeparatedByString. But it needs to indicate separator, so I could not. How can I do that?

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
bekkou68
  • 802
  • 1
  • 9
  • 20

3 Answers3

7

The proper way to split a string into an array is to do the following (as an NSString category method):

@interface NSString (ConvertToArray)
-(NSArray *)convertToArray;
@end

@implementation NSString (ConvertToArray)

- (NSArray *)convertToArray {
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    NSUInteger i = 0;
    while (i < self.length) {
        NSRange range = [self rangeOfComposedCharacterSequenceAtIndex:i];
        NSString *chStr = [self substringWithRange:range];
        [arr addObject:chStr];
        i += range.length;
    }

    return arr;
}

@end

NSArray *array = [@"Hello " convertToArray];
NSLog(@"array = %@", array);

Solutions that hardcode a range length of 1 will fail if the string contains Unicode characters of \U10000 or later. This include Emoji characters as well as many others.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
6

Here is my code:

@interface NSString (ConvertToArray)
-(NSArray *)convertToArray;
@end

@implementation NSString (ConvertToArray)

-(NSArray *)convertToArray
{
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    for (int i=0; i < self.length; i++) {
        NSString *tmp_str = [self substringWithRange:NSMakeRange(i, 1)];
        [arr addObject:[tmp_str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    return arr;
}
@end

:

- (void)foo
{
    NSString *exString = @"HELLO";
    NSArray *arr = [exString convertToArray];
    for (NSString *str  in arr) {
        NSLog(@"%@\n",str);
    }
}
honami
  • 121
  • 1
  • 5
  • category is nice to me. thanks! – bekkou68 Apr 09 '13 at 00:06
  • This solution will not work if the string contains any Unicode characters with a Unicode value greater than or equal to `\U10000`. Try this with Various Emoji characters, for example. – rmaddy Apr 09 '13 at 00:23
  • 1
    Your solution will also not work if the string contains any Regional Indicator. They are using surrogate pair. However your solution is better than my solution. – honami Apr 09 '13 at 00:48
  • Agreed. Unfortunately there is no API that will help with those flag characters. – rmaddy Apr 09 '13 at 02:08
2
NSString *string = @"HELLO";
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i < string.length; i ++) {
    [array addObject:[NSString stringWithFormat:@"%c", [string characterAtIndex:i]]];
}
ssantos
  • 16,001
  • 7
  • 50
  • 70
  • This won't work at all with Unicode characters beyond `\UFFFF`. And the `%c` format specifier won't work beyond `\UFF`. – rmaddy Apr 09 '13 at 00:31