Split NSString multiple times on the same separator
67,289
Solution 1
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
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.
Related videos on Youtube
Author by
Sam Parrish
Updated on July 05, 2022Comments
-
Sam Parrish almost 2 years
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?
-
Mark Amery over 10 yearsSomehow I suspect that almost all of the viewers and upvoters on this question and its answer were people simply looking for
NSString
's 'split' method, and discovering the answer here incidentally. -
boxed about 10 yearsThe first line is just creating an NSArray that you throw away at line 3.
-
-
Sam Parrish almost 13 yearsgreat thanks! just need to figure out how to create and show the UITableViewCell with 3 labels...
-
Simon Lee almost 13 yearsYou can either subclass UITableViewCell and do everything manually OR you can use one of the preset table view cell styles and use the content view to add an extra label. The apple guide details it all....
-
Simon Lee almost 13 years
-
Simon Lee almost 13 yearsCheck out the 'Customizing Cells' part in 'A closer look at table view cells' section
-
Tendulkar almost 13 yearsWhy I have written the code is In his code he has written the retain statement.No need of it.
-
Sam Parrish almost 13 yearsI have created the custom tableviewcell and used the same code, but when i configure the cell, what do i put for the third label?
-
pfrank over 10 yearsdon't use initWithFormat if not using a format? just: NSString *testString = @"blahblah";