2013-05-10 50 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 
)