How do you split NSString into component parts?

20,112

Solution 1

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.

Solution 2

There is a ready member function of NSString for doing that:

NSString* foo = @"safgafsfhsdhdfs/gfdgdsgsdg/gdfsgsdgsd";
NSArray* stringComponents = [foo componentsSeparatedByString:@"/"];

Solution 3

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.

Solution 4

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

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

or this one

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

That the only way I see, at the moment.

Share:
20,112
Graham Whitehouse
Author by

Graham Whitehouse

Software developer working in the UK!

Updated on September 03, 2020

Comments

  • Graham Whitehouse
    Graham Whitehouse over 3 years

    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...

  • Graham Whitehouse
    Graham Whitehouse over 13 years
    That worked brilliantly, thanks so much for the quick response :-)