views:

57

answers:

2

For example: NSString *strWord = "english";

The result NSArray would be something like: e n g l i s h

I think is possible to do it with

[NSString componentSeparatedByCharacter:somecharacter], but I don't know what that character is...

I wrote something like this to extract the character:

NSString *character;
for (int i=0; i<[strWord length]; i++) {
    character = [strWord substringWithRange:NSMakeRange(i, 1)];
}

Thanks for the help!

+1  A: 

Do this:

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];
}

You can also use this: http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/getCharacters:range:

Take a look here for more options:

NSString to char[]

How to convert an NSString to char

Leniel Macaferi
This code here leaks the characters array. you should probably just use `[NSMutableArray array]`. Your code will also fail if the character is non-ASCII - you want the %C format token instead for a unichar.
Kevin Ballard
Thanks for the advice!
Unikorn
+2  A: 

If you need to enumerate them and support iOS 4.0 or later, you could use

[strWord enumerateSubstringsInRange:NSMakeRange(0, [strWord length])
                            options:NSStringEnumerationByComposedCharacterSequences
                         usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
    // substring here contains each character in turn
}];

You could also just copy the characters into a buffer using -getCharacters:range: if you don't actually need them as an NSArray. Or you could just iterate over the string (using the block method, or by calling -characterAtIndex: repeatedly, or by copying out the entire buffer and iterating over that) and construct your own array.

Kevin Ballard
This is a good answer, but I would like to support version 3.2 and up.
Unikorn
The suggestions given in the second paragraph all work all the way back to iOS 2.0.
Kevin Ballard