79

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?

jscs
  • 63,694
  • 13
  • 151
  • 195
Sam Parrish
  • 1,377
  • 1
  • 11
  • 17
  • 6
    Somehow 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. – Mark Amery Aug 07 '13 at 16:29
  • The first line is just creating an NSArray that you throw away at line 3. – boxed Apr 21 '14 at 13:39

2 Answers2

173

The following line...

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

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

Simon Lee
  • 22,304
  • 4
  • 41
  • 45
  • great thanks! just need to figure out how to create and show the UITableViewCell with 3 labels... – Sam Parrish Jun 10 '11 at 09:33
  • You 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 Jun 10 '11 at 09:37
  • http://developer.apple.com/library/ios/#documentation/userexperience/conceptual/TableView_iPhone/AboutTableViewsiPhone/AboutTableViewsiPhone.html – Simon Lee Jun 10 '11 at 09:37
  • Check out the 'Customizing Cells' part in 'A closer look at table view cells' section – Simon Lee Jun 10 '11 at 09:38
  • I have created the custom tableviewcell and used the same code, but when i configure the cell, what do i put for the third label? – Sam Parrish Jun 10 '11 at 11:02
5

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.

Tendulkar
  • 5,550
  • 2
  • 27
  • 53