Graham Whitehouse
Graham Whitehouse

Reputation: 749

How do you split NSString into component parts?

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

Upvotes: 8

Views: 20218

Answers (5)

fspirit
fspirit

Reputation: 2547

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.

Upvotes: 1

VLegakis
VLegakis

Reputation: 470

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

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

Upvotes: 24

Nimrod
Nimrod

Reputation: 5133

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

Upvotes: 0

anon
anon

Reputation:

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.

Upvotes: 1

John Franklin
John Franklin

Reputation: 4912

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.

Upvotes: 4

Related Questions