How to split string into substrings on iOS?

IosObjective CIphoneStringSubstring

Ios Problem Overview


I received an NSString from the server. Now I want to split it into the substring which I need. How to split the string?

For example:

substring1:read from the second character to 5th character

substring2:read 10 characters from the 6th character.

Ios Solutions


Solution 1 - 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:@", "];

Solution 2 - Ios

NSString has a few methods for this:

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

Check the documentation for NSString for more information.

Solution 3 - Ios

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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChilly ZhongView Question on Stackoverflow
Solution 1 - IoscodelogicView Answer on Stackoverflow
Solution 2 - IosJoel LevinView Answer on Stackoverflow
Solution 3 - IosbenView Answer on Stackoverflow