method for replacing comma between quotes in NSString, please check my one
For parsing purposes it was necessary to replace commas inside quotas with space. I did not find and solution in NSString class and wrote this one. It works, but I would like to know your opinion if there is more simple approach:
- (NSString *) replaceBetweenQuotesInString:(NSString*)line {
const char *buffer = [line UTF8String];
NSMutableIndexSet *evenIndexes = [NSMutableIndexSet indexSet];
NSMutableIndexSe开发者_JAVA技巧t *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;
}
I have not tested this but since you do not seem to be concerned about escaped quotes:
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];
}
}
精彩评论