How to split items in a string separated by ","

19,335

Solution 1

use componentsSeparatedByString:

NSString *str = @"Hi,Hello,Bye";  
NSArray *arr = [str componentsSeparatedByString:@","];  
NSString *strHi = [arr objectAtIndex:0];  
NSString *strHello = [arr objectAtIndex:1];
NSString *strBye = [arr objectAtIndex:2];

Solution 2

NSString *str = @"Hi,Hello,Bye";

NSArray *aArray = [str componentsSeparatedByString:@","];

For more info, look at this post.

Solution 3

Well, the naïve approach would be to use componentsSeparatedByString:, as suggested in the other answers.

However, if your data is truly in the CSV format, you'd do well to consider using a proper CSV parser, such as this one (which I wrote): https://github.com/davedelong/CHCSVParser

Solution 4

Use [myString componentsSeparatedByString:@","].

Solution 5

NSArray *components = [@"Hi,Hello,Bye" componentsSeparatedByString:@","];

Apple's String Programming Guide will help you get up to speed.

Share:
19,335
Ankit Chauhan
Author by

Ankit Chauhan

Updated on June 08, 2022

Comments

  • Ankit Chauhan
    Ankit Chauhan almost 2 years

    In my App, data comes in String like this

    "Hi,Hello,Bye"
    

    I want to separate data by ","

    How can I do that?

  • Devang
    Devang over 12 years
    CSV example would be useful in future. Thanks
  • Josh Lehman
    Josh Lehman almost 9 years
    This is incorrect. The correct syntax is noted in the answer below: [str componentsSeparatedByString:@","];