Split NSString multiple times on the same separator

Objective CStringCocoa TouchCocoaNsstring

Objective C Problem Overview


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?

Objective C Solutions


Solution 1 - Objective C

The following line...

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

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

Solution 2 - Objective C

do like this.

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"];
	NSArray *testArray = [testString componentsSeparatedByString:@","];
	NSLog(@"%@",testArray);
	for(int i=0;i<[testArray count];i++){
		NSString *str=[testArray objectAtIndex:i];
	NSArray *aa=[str componentsSeparatedByString:@"|"];
	NSLog(@"%@",aa);
	}

No need of retain the array.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSam ParrishView Question on Stackoverflow
Solution 1 - Objective CSimon LeeView Answer on Stackoverflow
Solution 2 - Objective CTendulkarView Answer on Stackoverflow