1

Objective-C for iOS アプリで次の文字列を解析する必要があります

NSString *htmlString = @"12, 22, 'stringA','', 'stringB, stringC', 2,'stringD'";

このような配列にしたい

{
    @12,
    @22,
    @"stringA",
    @"emptySlotInfo",
    @"stringB, stringC",
    @2,
    @"stringD"
}

頭痛の種は @"strimb, stringC" です。

[htmlString componentsSeparatedByString:@","];

は大文字と小文字が区別されず、区切り文字としての @"'" も機能しません。

必要なコンポーネントを入手するにはどうすればよいですか?

4

1 に答える 1

2

NSScannerを使用できます。

をスキャンする'と、文字列が開始されたことを認識し,、次の を読み取るまで無視します'。オープニング'が読まれなかった場合は,

この cocoawithlove の記事が参考になるかもしれません。


早速試作品を作りました。私も NSScanner の専門家ではないため、最適化する必要がある可能性が高い

NSString *htmlString = @"12, 22, 'stringA','', 'stringB, stringC', 2,'stringD'";
NSScanner *scanner = [NSScanner scannerWithString:htmlString];

NSString *apostrophe = @"'";    // scanner needs to detect this
NSString *comma = @",";         // scanner needs to detect this
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:[NSString stringWithFormat:@"%@%@", apostrophe, comma]];
BOOL apostropheOpen = NO;       // is the scan location inside a single quoted substring?
NSInteger lastCommaIndex = -1;  // track last found comma's index
NSMutableArray *array = [NSMutableArray array];

while (![scanner isAtEnd]) {
    [scanner scanUpToCharactersFromSet:charSet intoString:NULL];
    NSString *charAtlocation = [htmlString substringWithRange:NSMakeRange([scanner scanLocation], 1)];
    if ([charAtlocation isEqualToString:apostrophe]){
        apostropheOpen = !apostropheOpen;                
    } else if ([charAtlocation isEqualToString:comma]){
        if (!apostropheOpen) {
            [array addObject: [scanner.string substringWithRange:NSMakeRange(lastCommaIndex+1, [scanner scanLocation]- lastCommaIndex-1)]];
            lastCommaIndex = [scanner scanLocation];
        }
    }
    [scanner setScanLocation:[scanner scanLocation]+1];
} ;

// scanner only dealt with the string until the last comma, probably one more value to handle
if (lastCommaIndex < [scanner scanLocation]){
    [array addObject: [scanner.string substringWithRange:NSMakeRange(lastCommaIndex+1, [scanner scanLocation]- lastCommaIndex-1)]];
}

// array contains seperated strings, but with blanks and apostrophes
// we will deal with them now
__block NSMutableArray *resultArray = [NSMutableArray array];
[array enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
    obj = [[obj stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
                stringByTrimmingCharactersInSet:charSet];
    if ([obj length] > 0)
        [resultArray addObject:obj];
    else
        [resultArray addObject:@"emptySlotInfo"];
}];

resultArray には以下が含まれます

(
12,
22,
stringA,
emptySlotInfo,
stringB, stringC,
2,
stringD
)
于 2012-10-15T20:16:47.113 に答える