2013-05-10 52 views
2

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

我解释一下:

我的字符串:

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

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

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

的目的是获得一个阵列:

(
black, 
"red, blue", 
yellow 
) 
+1

究竟被认为是一个分离器?一个没有空格的逗号?这是正确的定义吗? – 2013-05-10 09:55:21

回答

8

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

+0

+1伟大的逻辑.. – 2013-05-10 10:01:51

+1

我正在这个方向与NSRegularExpression然后stringByReplacingMatchesInString – masgar 2013-05-10 10:05:25

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

+0

最佳答案!只有你不需要循环的解决方案。在我的情况下,我在我想保留的逗号之前有一个转义字符'\',所以在调用'componentsSeparatedByString'之前,我删除了转义字符 – 2015-06-28 13:48:23

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); 
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 
)