How to split string into substrings on iOS?

后端 未结 3 470
闹比i
闹比i 2020-12-02 09:37

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:

substrin

相关标签:
3条回答
  • 2020-12-02 10:08

    NSString has a few methods for this:

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

    Check the documentation for NSString for more information.

    0 讨论(0)
  • 2020-12-02 10:15

    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;
    }
    
    0 讨论(0)
  • 2020-12-02 10:24

    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:@", "];
    
    0 讨论(0)
提交回复
热议问题