3

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!

Unikorn
  • 1,140
  • 1
  • 13
  • 27
  • What do you mean by a "character"? An `NSString` holds a sequence of `unichar`, which is a UTF-16 character, but a single Unicode character may be represented by multiple UTF-16 characters. – JWWalker Apr 25 '15 at 00:10

2 Answers2

5

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.

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
4

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

Community
  • 1
  • 1
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
  • 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. – Lily Ballard Oct 29 '10 at 02:06