How to split string into substrings on iOS?

You can also split a string by a substring, using NString's componentsSeparatedByString method.

Example from documentation:

NSString *list = @"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:@", "];

NSString has a few methods for this:

[myString substringToIndex:index];
[myString substringFromIndex:index];
[myString substringWithRange:range];

Check the documentation for NSString for more information.


I wrote a little method to split strings in a specified amount of parts. Note that it only supports single separator characters. But I think it is an efficient way to split a NSString.

//split string into given number of parts
-(NSArray*)splitString:(NSString*)string withDelimiter:(NSString*)delimiter inParts:(int)parts{
    NSMutableArray* array = [NSMutableArray array];

    NSUInteger len = [string length];
    unichar buffer[len+1];

    //put separator in buffer
    unichar separator[1];
    [delimiter getCharacters:separator range:NSMakeRange(0, 1)];

    [string getCharacters:buffer range:NSMakeRange(0, len)];

    int startPosition = 0;
    int length = 0;
    for(int i = 0; i < len; i++) {

        //if array is parts-1 and the character was found add it to array
        if (buffer[i]==separator[0] && array.count < parts-1) {
            if (length>0) {
                [array addObject:[string substringWithRange:NSMakeRange(startPosition, length)]];

            }

            startPosition += length+1;
            length = 0;

            if (array.count >= parts-1) {
                break;
            }

        }else{
            length++;
        }

    }

    //add the last part of the string to the array
    [array addObject:[string substringFromIndex:startPosition]];

    return array;
}