views:

37

answers:

1

Hi, Say I have the following string "Center-World" and I want to separate this string in two different strings but I want the dash to be part of "Center". With the code below I got a string with ["Center","World"] and I want something that returns ["Center-","World"].

Here is my code:

NSCharacterSet *stringDelimiters = [NSCharacterSet characterSetWithCharactersInString:@" :-"]; NSArray *cellContentWords = [cell.text componentsSeparatedByCharactersInSet:stringDelimiters];

Any suggestions?

thanks in advance.

A: 

I had need of something like this recently. I wanted to break up a selector string (ex: initWithFoo:bar:baz:) into its various components: (ex: initWithFoo:, bar:, and baz:). You've found, as did I, that componentsSeparatedByString: doesn't quite cut it. I therefore created an NSString category to do what I was looking for:

- (NSArray *) selectorComponents {
    NSMutableArray * components = [NSMutableArray array];
    NSMutableString * scratchString = [self mutableCopy];
    while ([scratchString rangeOfString:@":"].location != NSNotFound) {
        NSRange componentRange = NSMakeRange(0, [scratchString rangeOfString:@":"].location+1);
        NSString * component = [scratchString substringWithRange:componentRange];
        [components addObject:component];
        [scratchString replaceCharactersInRange:componentRange withString:@""];
    }
    [scratchString release];
    return components;
}

You'll want to change from searching for @":" to @"-", but after that it should work as you're expecting.

Dave DeLong