在同一分隔符上多次拆分NSString [英] Split NSString multiple times on the same separator
本文介绍了在同一分隔符上多次拆分NSString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前收到的字符串如下:
@Sam | 26,Hannah | 22,Adam | Carly | 32,Jan | 54
我这样分割:
testArray = [[NSArray alloc] init];
NSString * testString = [[NSString alloc] initWithFormat:@Sam | 26,Hannah | 22,Adam | 30,Carlie | 32,Jan | 54,Steve | 56,Matty | 24,Bill | 30,Rob | 30,Jason | 33,Mark | 22,Stuart | 54,Kevin | 30];
testArray = [testString componentsSeparatedByString:@,];
dict = [NSMutableDictionary dictionary];
for(NSString * s in testArray){
testArray2 = [s componentsSeparatedByString:@|];
[dict setObject:[testArray2 objectAtIndex:1] forKey:[testArray2 objectAtIndex:0]];
}
我现在将收到一个这样的字符串:
@Sam | 26 |开发人员,Hannah | 22 | Team Leader,Adam | 30 | Director,Carlie | 32 | PA,Jan | 54 |
我可以(以及如何)使用与上述相同的方法, |
$解决方案
> testArray2 = [s componentsSeparatedByString:@|];
会使数组现在包含3个项目,而不是2 .....再次分割!
I am currently receiving a string like this:
@"Sam|26,Hannah|22,Adam|30,Carlie|32,Jan|54"
And I am splitting it like this:
testArray = [[NSArray alloc] init];
NSString *testString = [[NSString alloc] initWithFormat:@"Sam|26,Hannah|22,Adam|30,Carlie|32,Jan|54,Steve|56,Matty|24,Bill|30,Rob|30,Jason|33,Mark|22,Stuart|54,Kevin|30"];
testArray = [testString componentsSeparatedByString:@","];
dict = [NSMutableDictionary dictionary];
for (NSString *s in testArray) {
testArray2 = [s componentsSeparatedByString:@"|"];
[dict setObject:[testArray2 objectAtIndex:1] forKey:[testArray2 objectAtIndex:0]];
}
I will now be receiving a string like this:
@"Sam|26|Developer,Hannah|22|Team Leader,Adam|30|Director,Carlie|32|PA,Jan|54|Cleaner"
Can I (and how) use the same method as above to separate the string more than once using the "|" separator?
解决方案
The following line...
testArray2 = [s componentsSeparatedByString:@"|"];
will cause the array to now contain 3 items, instead of 2..... no need to split again!
这篇关于在同一分隔符上多次拆分NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文