I want to split an NSString
into an NSArray
. For example, given:
NSString *myString=@\"ABCDEF\";
I want an
Without loop you can use this:
NSString *myString = @"ABCDEF";
NSMutableString *tempStr =[[NSMutableString alloc] initWithString:myString];
if([myString length] != 0)
{
NSError *error = NULL;
// declare regular expression object
NSRegularExpression *regex =[NSRegularExpression regularExpressionWithPattern:@"(.)" options:NSMatchingReportCompletion error:&error];
// replace each match with matches character + e.g. 'A' with 'A '
[regex replaceMatchesInString:tempStr options:NSMatchingReportCompletion range:NSMakeRange(0,[myString length]) withTemplate:@"$0 "];
// trim last character
[tempStr replaceCharactersInRange:NSMakeRange([tempStr length] - 1, 1) withString:@""];
// split into array
NSArray * arr = [tempStr componentsSeparatedByString:@" "];
// print
NSLog(@"%@",arr);
}
This solution append space in front of each character with the help of regular expression and uses componentsSeparatedByString
with
to return an array