在NSString中替换逗号之间的逗号的方法,请检查我的

时间:2011-07-25 09:33:04

标签: objective-c xcode nsstring

为了解析目的,有必要用空格替换配额内的逗号。我没有在NSString类中找到并解决这个问题。 它有效,但如果有更简单的方法,我想知道你的意见:

- (NSString *) replaceBetweenQuotesInString:(NSString*)line {

    const char *buffer = [line UTF8String];

    NSMutableIndexSet *evenIndexes = [NSMutableIndexSet indexSet];    

    NSMutableIndexSet *oddIndexes = [NSMutableIndexSet indexSet];

    BOOL evenOdd = YES;

    for (unsigned int i = 0; i < [line length]; i++) {


        if (buffer[i] == '"'){
            if (evenOdd)
                [evenIndexes addIndex:i];
            else
                [oddIndexes addIndex:i];

        evenOdd = !evenOdd;
        }
    }

    if ([evenIndexes count] != [oddIndexes count] )
        [evenIndexes removeIndex:[evenIndexes lastIndex]];

    int totalRanges = (int) [evenIndexes count];

    for (int i = 0; i < totalRanges; i++) {

        NSRange range = NSMakeRange([evenIndexes firstIndex], [oddIndexes firstIndex] - [evenIndexes firstIndex]);
        [evenIndexes removeIndex:[evenIndexes firstIndex]];
        [oddIndexes removeIndex:[oddIndexes firstIndex]];
        line = [line stringByReplacingOccurrencesOfString:@"," withString:@" " options:NSLiteralSearch range:range];

    }

    [evenIndexes removeAllIndexes];
    [oddIndexes removeAllIndexes];    

    return line;

}

1 个答案:

答案 0 :(得分:2)

我没有对此进行测试,但因为您似乎并不关心转义引号:

NSMutableString* result = [[NSMutableString alloc] init];
NSArray* components = [line componentsSeparatedByString: @"\""];
for (int i = 0 ; i < [components count] ; ++i)
{
    if (i % 2 == 0)
    {
        [result appendString: [components objectAtIndex: i]];
    }
    else
    {
        NSString* fixed = [[components objectAtIndex: i] stringByReplacingOccurrencesOfString: @"," 
                                                                                   withString: @" "];
        [result appendFormat: @"\"%@\"", fixed];
    }
}