11

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?

EmptyStack
  • 51,274
  • 23
  • 147
  • 178
gopal
  • 212
  • 1
  • 4
  • 12

7 Answers7

25
NSMutableArray *letterArray = [NSMutableArray array];
NSString *letters = @"ABCDEFक्";
[letters enumerateSubstringsInRange:NSMakeRange(0, [letters length]) 
                            options:(NSStringEnumerationByComposedCharacterSequences) 
                         usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
    [letterArray addObject:substring];
}];

for (NSString *i in letterArray){
    NSLog(@"%@",i);
}

results in

A
B
C
D
E
F

क्

enumerateSubstringsInRange:options:usingBlock: available for iOS 4+ can enumerate a string with different styles. One is called NSStringEnumerationByComposedCharacterSequences, what will enumerate letter by letter but is sensitive to surrogate pairs, base characters plus combining marks, Hangul jamo, and Indic consonant clusters, all referred as Composed Character

Note, that the accepted answer "swallows" and breaks क् into and .

Community
  • 1
  • 1
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
  • 2
    Definitely the correct way. I made a category out of it: https://gist.github.com/4634479 – Berik Jan 25 '13 at 15:02
  • In Swift this now takes only one line. See https://stackoverflow.com/a/44675708/364446 – KPM Jun 21 '17 at 12:11
12

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

Fernando Cervantes
  • 2,962
  • 2
  • 23
  • 34
11
NSMutableArray *chars = [[NSMutableArray alloc] initWithCapacity:[theString length]];
for (int i=0; i < [theString length]; i++) {
    NSString *ichar  = [NSString stringWithFormat:@"%C", [theString characterAtIndex:i]];
    [chars addObject:ichar];
}
Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
yan.kun
  • 6,820
  • 2
  • 29
  • 38
  • 5
    This is a naïve solution that doesn't handle surrogate pairs or composed characters, as @JeremyP astutely brought up in his comment on the question. Also, don't forget to release the array when not using GC or ARC. – Peter Hosey Jul 05 '11 at 11:16
4

This link contains examples to split a string into a array based on sub strings and also based on strings in a character set. I hope that post may help you.

here is the code snip

NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
    NSString *ichar  = [NSString stringWithFormat:@"%c", [myString characterAtIndex:i]];
    [characters addObject:ichar];
}
swiftBoy
  • 35,607
  • 26
  • 136
  • 135
EmptyStack
  • 51,274
  • 23
  • 147
  • 178
  • 4
    Consider improving your post since your answer is essentially a link. See: [Are answers that just contain links elsewhere really “good answers”?](http://meta.stackexchange.com/q/8231/156620) and [Why is linking bad?](http://meta.stackexchange.com/q/7515/156620) –  Jul 05 '11 at 08:45
  • @Bavarious, Is that enough? ;-) – EmptyStack Jul 05 '11 at 08:52
  • 1
    @Bavarious agree, The answer having only link are no more useful once URL goes dead. So **EmptyStack** please! try to post some code that may help in future for anyone. Thanks!! – swiftBoy Apr 22 '13 at 06:25
1

Without loop you can use this:

NSString *myString = @"ABCDEF";
NSMutableString *tempStr =[[NSMutableString alloc] initWithString:myString];

if([myString length] != 0)
{
    NSError  *error  = NULL;

    // declare regular expression object
    NSRegularExpression *regex =[NSRegularExpression regularExpressionWithPattern:@"(.)" options:NSMatchingReportCompletion error:&error];

    // replace each match with matches character + <space> e.g. 'A' with 'A '
    [regex replaceMatchesInString:tempStr options:NSMatchingReportCompletion range:NSMakeRange(0,[myString length]) withTemplate:@"$0 "];

    // trim last <space> character
    [tempStr replaceCharactersInRange:NSMakeRange([tempStr length] - 1, 1) withString:@""];

    // split into array
    NSArray * arr = [tempStr componentsSeparatedByString:@" "];

    // print
    NSLog(@"%@",arr);
}

This solution append space in front of each character with the help of regular expression and uses componentsSeparatedByString with <space> to return an array

0

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"

KPM
  • 10,558
  • 3
  • 45
  • 66
-1

In Swift, this becomes very simple.

Swift 3:

myString.characters.map { String($0) }

Swift 4:

myString.map { String($0) }
KPM
  • 10,558
  • 3
  • 45
  • 66