2

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?

Georg Schölly
  • 124,188
  • 49
  • 220
  • 267
Lorenzo
  • 133
  • 1
  • 2
  • 6

3 Answers3

3

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.

Black Frog
  • 11,595
  • 1
  • 35
  • 66
1

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)

Ciryon
  • 2,637
  • 3
  • 31
  • 33
1

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]];
Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144