Lorenzo
Lorenzo

Reputation: 133

How to split a string?

I have a string made of three strings like this

NSString *first = ..;
NSString *second = ..;
NSString *third = ..;

NSString joinedString;
joinedString = [NSString stringWithFormat:@"%@ - %@ (%@)", first, second, third];

Now I need to get back the three original strings from joinedString. I've read somewhere that I should use NSScanner for this. Any ideas how that might work?

Upvotes: 2

Views: 2573

Answers (3)

Black Frog
Black Frog

Reputation: 11713

Given the example you provided in your question, you could do the following:

// characters we are going to split at
NSString *sep = @" -()";
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:sep];
NSArray *strings = [joinedString componentsSeparatedByCharactersInSet:set];

// This is the simple way provided that the strings doesn't have spaces in them.

I would use NSScanner with larger strings that have variable information and you want to find that needle in the haystack.

Upvotes: 3

Evan Mulawski
Evan Mulawski

Reputation: 55334

You can use componentsSeparatedByCharactersInSet::

NSString *chars = @"-()";
NSArray *split = [joinedString componentsSeparatedByCharactersInSet:[NSCharacterset characterSetWithCharactersInString:chars]];

You can then trim the beginning/end spaces:

stringFromArray = [stringFromArray stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

Upvotes: 1

Ciryon
Ciryon

Reputation: 2777

If you got the exact pattern as mentioned in your post you can use NSRegularExpression (iOS 4+):

NSString *regexStr = @"(.*)\s-\s(.*)\s\((.*)\)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:nil];
NSArray *results = [regex matchesInString:joinedString options:0 range:NSMakeRange(0, [joinedString length])];
NSString *string1 = [results objectAtIndex:0];
...

(no error handling and not able to verify it right now)

Upvotes: 1

Related Questions