iPhone Development 101

iPhone 101

Code Tips

Resources

Links

Follow

TwitterRSSE-mail

More

iPhone Development 101: Objective-C: Strings:
Split a String into an Array

Split a string into an array of strings by using NSString's componentsSeparatedByString:

NSString *myString = @"This is a test";
NSArray *myWords = [myString componentsSeparatedByString:@" "];

// myWords is now: [@"This", @"is", @"a", @"test"]

If you need to split on a set of several different characters, use NSString's componentsSeparatedByCharactersInSet:

NSString *myString = @"Foo-bar/blee";
NSArray *myWords = [myString componentsSeparatedByCharactersInSet:
                      [NSCharacterSet characterSetWithCharactersInString:@"-/"]
                    ];

// myWords is now: [@"Foo", @"bar", @"blee"]

The separator string can't be blank. If you need to separate a string into its individual characters, just loop through the length of the string and convert each char into a new string:

NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
    NSString *ichar  = [NSString stringWithFormat:@"%c", [myString characterAtIndex:i]];
    [characters addObject:ichar];
}

More String Functions

Additional References


TopHome