2011-03-28 326 views
2

我有這樣如何拆分字符串?

NSString *first = ..; 
NSString *second = ..; 
NSString *third = ..; 

NSString joinedString; 
joinedString = [NSString stringWithFormat:@"%@ - %@ (%@)", first, second, third]; 

現在我需要從joinedString找回三個原始字符串由三根弦的字符串。我讀過一些我應該使用NSScanner的地方。任何想法如何可能工作?

回答

3

鑑於你在你的問題中提供的例子,你可以做到以下幾點:

// characters we are going to split at 
NSString *sep = @" -()"; 
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:sep]; 
NSArray *strings = [joinedString componentsSeparatedByCharactersInSet:set]; 

// This is the simple way provided that the strings doesn't have spaces in them. 

我會用NSScanner與具有可變信息和你想找到在草堆該針頭大的字符串。

+0

'componentsSeparatedByString'不起作用。檢查文檔。 – 2011-03-28 12:41:52

+0

謝謝,我已更正我的代碼。 – 2011-03-28 12:46:21

+0

謝謝,完美的工作! – Lorenzo 2011-03-28 16:07:28

1

如果您在您的文章,您可以使用NSRegularExpression(iOS 4以上)提到得到了確切的模式:

NSString *regexStr = @"(.*)\s-\s(.*)\s\((.*)\)"; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:nil]; 
NSArray *results = [regex matchesInString:joinedString options:0 range:NSMakeRange(0, [joinedString length])]; 
NSString *string1 = [results objectAtIndex:0]; 
... 

(沒有錯誤處理和無法驗證它現在)

1

你可以使用componentsSeparatedByCharactersInSet:

NSString *chars = @"-()"; 
NSArray *split = [joinedString componentsSeparatedByCharactersInSet:[NSCharacterset characterSetWithCharactersInString:chars]]; 

然後,您可以修剪開始/結束空間:

stringFromArray = [stringFromArray stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];