2012-04-27 72 views
1

我有一個字符串,其中包含一些帶句號和逗號的文本。我想將它轉換爲基於逗號和句點的NSArray。我使用這種方法根據一種情況進行分離,但我怎麼用兩種方法來做到這一點?將NSString轉換爲具有多個條件的NSArray

componentsSeparatedByString: 

謝謝。

回答

4
NSString *tempTextOut = [NSString stringWithFormat:@"jdnfj,adsfsajfhkj,hasdfjhdsjkfh,hdsufhajkdsfhk"]; 
NSMutableArray *array = [[tempTextOut componentsSeparatedByString: @","] mutableCopy]; 
NSLog(@"%@",array); 

>>輸出1

jdnfj, 
adsfsajfhkj, 
hasdfjhdsjkfh, 
hdsufhajkdsfhk 

NSString *tempTextOut = [NSString  stringWithFormat:@"jdnfj,adsfsajfhkj,,,hasdfjhdsjkfh,,,,hdsufhajkdsfhk"]; 
NSMutableArray *array = [[tempTextOut componentsSeparatedByString: @",,,"] mutableCopy]; 
NSLog(@"%@",array); 

>> OUTPUT2

"jdnfj,adsfsajfhkj", 
hasdfjhdsjkfh, 
",hdsufhajkdsfhk" 

希望,這會幫助你..

+0

+1 ....感謝您的努力! – TommyG 2012-04-27 03:46:23

+0

永遠歡迎... :) – Nit 2012-04-27 03:51:00

+0

我只是混淆了一些投下了答案... – Nit 2012-04-27 03:57:01

5

您需要創建NSCharacterSet用逗號,並在其中一個點,用這個方法:

- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator 

下面是一個例子:

NSArray *arr = [str componentsSeparatedByCharactersInSet: 
     [NSCharacterSet characterSetWithCharactersInString:@",."]]; 
+0

+1感謝您的幫助! – TommyG 2012-04-27 03:46:44

9

您可以使用componentsSeparatedByCharactersInSet:

例如:

NSString *str = @"1,2.3"; 

NSArray *arr = [str componentsSeparatedByCharactersInSet: 
       [NSCharacterSet characterSetWithCharactersInString:@",."]]; 

請參考NSString Class Reference

+0

+1感謝您的幫助! – TommyG 2012-04-27 04:05:53

相關問題