NSString to NSArray

Viewed 19998

I want to split an NSString into an NSArray. For example, given:

NSString *myString=@"ABCDEF";

I want an NSArray like:

NSArray *myArray={A,B,C,D,E,F};

How to do this with Objective-C and Cocoa?

7 Answers

Conversion

NSString * string = @"A B C D E F";
NSArray * array = [string componentsSeparatedByString:@" "];
//Notice that in this case I separated the objects by a space because that's the way they are separated in the string

Logging

NSLog(@"%@", array);

Console

This is what the console returned

Swift 4.2:

String to Array

let list = "Karin, Carrie, David"

let listItems = list.components(separatedBy: ", ")

Output : ["Karin", "Carrie", "David"]

Array to String

let list = ["Karin", "Carrie", "David"]

let listStr = list.joined(separator: ", ")

Output : "Karin, Carrie, David"

Related