Ad

Our DNA is written in Swift
Jump

String to Array of Characters

Michael asks:

“How do I split the characters in an NSString into an NSArray? In BASIC I could split a string with empty character, but in Object C this does not work”

One way to do it is to just get one character substrings:

NSString *s = @"Hello World";
int i;
NSMutableArray *m = [[NSMutableArray alloc] init];
 
for (i=0;i< [s length]; i++)
{
	[m addObject:[s substringWithRange:NSMakeRange(i, 1)]];
}
 
NSLog([m description]);  // most NS* objects have a useful description
 
[m release];  // don't forget

In Objective C every time you need a starting point and then a length from there it’s call an NSRange. Conveniently there is also a *Make macro for most structures like this. So in this case you just NSMakeRange(position,length) and pass this to a substringWithRange.


Categories: Q&A

Leave a Comment