Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert NSString to NSArray with characters one by one in Objective-C [duplicate]

Tags:

objective-c

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?

like image 420
bekkou68 Avatar asked Dec 06 '22 08:12

bekkou68


2 Answers

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.

like image 195
rmaddy Avatar answered Jun 11 '23 12:06

rmaddy


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);
    }
}
like image 21
honami Avatar answered Jun 11 '23 11:06

honami