简体   繁体   中英

How to use NSScanner or componentsSeperatedByString

I have a {"Red","Blue","Green","Yellow"} returned as string. How to process this to add to an array ?

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSString* sampleString = @"{\"Red\",\"Blue\",\"Green\",\"Yellow\"}";
    NSArray* components = [sampleString componentsSeperatedByString:@"\"{"];

    [pool drain];
    return 0;
}

Updated Code#

NSString* sampleString = @"{\"Red\",\"Blue\",\"Green\",\"Yellow\"}";

NSMutableArray *rows = [NSMutableArray array];

// Get newline character set
NSMutableCharacterSet *removeCharacterSet = (id)[NSMutableCharacterSet characterSetWithCharactersInString:@"{(,}"];
[removeCharacterSet formIntersectionWithCharacterSet:[[NSCharacterSet whitespaceCharacterSet] invertedSet]];

// Characters that are important to the parser
NSMutableCharacterSet *importantCharactersSet = (id)[NSMutableCharacterSet characterSetWithCharactersInString:@"\""];
[importantCharactersSet formUnionWithCharacterSet:removeCharacterSet];

// Create scanner, and scan string
NSScanner *scanner = [NSScanner scannerWithString:sampleString];
[scanner setCharactersToBeSkipped:nil];
while ( ![scanner isAtEnd] ) 
{        
    BOOL insideQuotes = NO;
    BOOL finishedRow = NO;
    NSMutableArray *columns = [NSMutableArray arrayWithCapacity:10];
    NSMutableString *currentColumn = [NSMutableString string];
    while ( !finishedRow ) 
    {
        NSString *tempString;
        if ( [scanner scanUpToCharactersFromSet:importantCharactersSet intoString:&tempString] ) {
            [currentColumn appendString:tempString];
        }

        if ( [scanner isAtEnd] ) {
            if ( ![currentColumn isEqualToString:@""] ) [columns addObject:currentColumn];
            finishedRow = YES;
        }
        else if ( [scanner scanCharactersFromSet:removeCharacterSet intoString:&tempString] ) {
            if ( insideQuotes ) {
                // Add line break to column text
                [currentColumn appendString:tempString];
            }
            else {
                // End of row
                if ( ![currentColumn isEqualToString:@""] ) [columns addObject:currentColumn];
                finishedRow = YES;
            }
        }
        else if ( [scanner scanString:@"\"" intoString:NULL] ) {
            if ( insideQuotes && [scanner scanString:@"\"" intoString:NULL] ) {
                // Replace double quotes with a single quote in the column string.
                [currentColumn appendString:@"\""]; 
            }
            else {
                // Start or end of a quoted string.
                insideQuotes = !insideQuotes;
            }
        }
        else if ( [scanner scanString:@"," intoString:NULL] ) {  
            if ( insideQuotes ) {
                [currentColumn appendString:@","];
            }
            else {
                // This is a column separating comma
                [columns addObject:currentColumn];
                currentColumn = [NSMutableString string];
                [scanner scanCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString:NULL];
            }
        }
    }
    if ( [columns count] > 0 ) [rows addObject:columns];
}
NSLog(@"This String:%@",[rows objectAtIndex:0]);

I got code from http://www.macresearch.org/cocoa-scientists-part-xxvi-parsing-csv-data . Now the output is This String:( Red ), How to get rid of "(" ")" ?

Here's all you need to scan the sample you've provided using an instance of NSScanner :

NSScanner *scanner = [NSScanner scannerWithString:@"{\"Red\",\"Blue\",\"Green\",\"Yellow\"}"];
NSMutableCharacterSet *charactersToSkip = [NSMutableCharacterSet punctuationCharacterSet];
[scanner setCharactersToBeSkipped:charactersToSkip]; 
NSMutableArray *substrings = [NSMutableArray array];
NSString *substring = @"";
while (![scanner isAtEnd]) {
    [scanner scanUpToCharactersFromSet:charactersToSkip intoString:&substring];
    [scanner scanCharactersFromSet:charactersToSkip intoString:NULL];
    [substrings addObject:substring];
}

NSLog(@"%@", substrings);

Note that if you substituted parens for curly braces, all you'd need to do to create an array of strings from the sample would be:

NSString *sampleString = @"(\"Red\",\"Blue\",\"Green\",\"Yellow\")";
NSArray *strings = [sampleString propertyList];
NSLog(@"%@", strings);

...but I'm not really clear on what you need to accomplish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM