Explode/split NSString

I’m back to iPhone programming and, yeah, sometimes I tend to forget the simplest things. So here it is, a way to split a string by some separator string (in our case – “/”)

componentsSeparatedByString

NSString *exampleURL = @"http://foobarpig.com/iphone/";
NSArray *pieces = [exampleURL componentsSeparatedByString:@"/"];
NSLog(@"%@", pieces);

And result is a nice array of strings separated by “/”:

"http:",
"",
"foobarpig.com",
iphone,
""

componentsSeparatedByCharactersInSet

In cases, when you need to split your string by more than one separator, use componentsSeparatedByCharactersInSet function.

NSString *exampleURL = @"http://foobarpig.com/iphone/";
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"/:."];  // note 3 separators: "/", ":" and "."
NSArray *pieces = [exampleURL componentsSeparatedByCharactersInSet:charSet];
NSLog(@"%@", pieces);

Result:

    http,
    "",
    "",
    foobarpig,
    com,
    iphone,
    ""

Tags: , , ,

One response

  1. Posted April 25, 2011 at 00:50 | Permalink

    Great website. A lot of helpful info here. I¡¦m sending it to several pals ans additionally sharing in delicious. And obviously, thanks in your effort!

Leave a Reply