Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

objective c - Split NSString multiple times on the same separator

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following line...

testArray2 = [s componentsSeparatedByString:@"|"];

will cause the array to now contain 3 items, instead of 2..... no need to split again!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...