views:

75

answers:

4

Hi!

In XCode, if I have an NSString containing a number, ie @"12345", how do I split it into an array representing component parts, ie "1", "2", "3", "4", "5"... There is a componentsSeparatedByString on the NSString object, but in this case there is no delimiter...

Any help is much appreciated!

Graham

+3  A: 

It may seem like characterAtIndex: would do the trick, but that returns a unichar, which isn't an NSObject-derived data type and so can't be put into an array directly. You'd need to construct a new string with each unichar.

A simpler solution is to use substringWithRange: with 1-character ranges. Run your string through a simple for (int i=0;i<[myString length];i++) loop to add each 1-character range to an NSMutableArray.

John Franklin
That worked brilliantly, thanks so much for the quick response :-)
Graham Whitehouse
+1  A: 

A NSString already is an array of it’s components, if by components you mean single characters. Use [string length] to get the length of the string and [string characterAtIndex:] to get the characters.

If you really need an array of string objects with only one character you will have to create that array yourself. Loop over the characters in the string with a for loop, create a new string with a single character using [NSString stringWithFormat:] and add that to your array. But this usually is not necessary.

Sven
A: 

Don't know if this works for what you want to do but:

const char *foo = [myString UTF8String]
char third_character = foo[2];

Make sure to read the docs on UTF8String

Nimrod
A: 

In your case, since you have no delimiter, you have to get separate chars by

  • (void)getCharacters:(unichar *)buffer range:(NSRange)aRange

or

  • (unichar)characterAtIndex:(NSUInteger) index inside a loop.

That the only way I see, at the moment.

fspirit