使用componentsSeparatedByString拆分NSString

时间:2013-05-10 09:48:49

标签: objective-c nsstring foundation

我有一个我需要拆分的字符串。使用componentsSeparatedByString会很容易但我的问题是分隔符是一个逗号,但我可以使用不是分隔符的逗号。

我解释说:

我的字符串:

NSString *str = @"black,red, blue,yellow";

红色和蓝色之间的逗号不得视为分隔符。

我可以确定逗号是否是分隔符,或者检查是否有空格。

目标是获得一个数组:

(
black,
"red, blue",
yellow
)

4 个答案:

答案 0 :(得分:8)

这很棘手。首先用'|'替换所有出现的','(逗号+空格)然后使用组件分离的方法。完成后,再次替换“|”用','(逗号+空格)。

答案 1 :(得分:4)

只是为了完成图片,这是一个使用正则表达式直接识别逗号后面没有空格的解决方案,正如您在问题中解释的那样。

正如其他人所建议的那样,使用此模式替换为临时分隔符字符串并将其拆分。

NSString *pattern = @",(?!\\s)"; // Match a comma not followed by white space.
NSString *tempSeparator = @"SomeTempSeparatorString"; // You can also just use "|", as long as you are sure it is not in your input.

// Now replace the single commas but not the ones you want to keep
NSString *cleanedStr = [str stringByReplacingOccurrencesOfString: pattern
                                                      withString: tempSeparator
                                                         options: NSRegularExpressionSearch
                                                           range: NSMakeRange(0, str.length)];

// Now all that is needed is to split the string
NSArray *result = [cleanedStr componentsSeparatedByString: tempSeparator];   

如果您不熟悉所使用的正则表达式模式,(?!\\s)是一个负向前瞻,您可以找到相当好的解释,例如here

答案 2 :(得分:1)

以下是 cronyneaus4u 解决方案的编码实现:

NSString *str = @"black,red, blue,yellow";
str = [str stringByReplacingOccurrencesOfString:@", " withString:@"|"];
NSArray *wordArray = [str componentsSeparatedByString:@","];
NSMutableArray *finalArray = [NSMutableArray array];
for (NSString *str in wordArray)
{
    str = [str stringByReplacingOccurrencesOfString:@"|" withString:@", "];
    [finalArray addObject:str];
}
NSLog(@"finalArray = %@", finalArray);

答案 3 :(得分:0)

NSString *str = @"black,red, blue,yellow";
NSArray *array = [str componentsSeparatedByString:@","];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
for (int i=0; i < [array count]; i++) {
    NSString *str1 = [array objectAtIndex:i];
    if ([[str1 substringToIndex:1] isEqualToString:@" "]) {
        NSString *str2 = [finalArray objectAtIndex:(i-1)];
        str2 = [NSString stringWithFormat:@"%@,%@",str2,str1];
        [finalArray replaceObjectAtIndex:(i-1) withObject:str2];
    }
    else {
        [finalArray addObject:str1];
    }
}

NSLog(@"final array count : %d description : %@",[finalArray count],[finalArray description]);

输出:

final array count : 3 description : (
black,
"red, blue",
yellow
)