开发者

Separate strings and include separating character in one of the returned components

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开发者_Python百科 something that returns ["Center-","World"].

Here is my code:

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

Any suggestions?

thanks in advance.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜