为了解析目的,有必要用空格替换配额内的逗号。我没有在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;
}
答案 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];
}
}