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?
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With