0

I want to add every Character in an NSArray ("123" -> To NSArray with "1","2","3"). I tested componentsSeparatedByString:@"" and componentsSeparatedByString:nil, but it doesn't work, can anyone help me?

Monolo
  • 18,205
  • 17
  • 69
  • 103
BatWayne
  • 21
  • 2

2 Answers2

7

Depending on your needs, you may wish to enumerate the string by composed characters, which takes into account the different ways to encode accented characters.

It may not be a big issue, but if you use enumerateSubstringsInRange:options:usingBlock: at least it is handled. The code can look like this:

NSMutableArray *result;  

NSString *string = @"Genève, Zu\u0308rich, Bellinzona";
//                           ^
//      What humans know as: Zürich

result = [NSMutableArray array];
[string enumerateSubstringsInRange: NSMakeRange(0,string.length)
                           options: NSStringEnumerationByComposedCharacterSequences
                        usingBlock: ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
                            // If you want to see the way the string has been split
                            NSLog(@"%@", substring);
                            [result addObject: substring];
                        }
];

Notice that "è" is a single character but "ü" has been encoded as a composed character. Both are still correctly identified for use in the loop. If you use characterAtIndex: "ü" will be split in two (the u and the ¨), which is very likely not what you want.

Monolo
  • 18,205
  • 17
  • 69
  • 103
  • Very good answer. Many people just forget about non-ASCII characters and ignore all the complicated rules how strings can be composed (e.g. read up Unicode normalization forms). – Mike Lischke May 14 '13 at 13:29
-1

You can use like this,

for (int i=0; i < [myString length]; i++) {
    ... [myString characterAtIndex:i]
   // You can then decide how to assign a value to each individual string, via a switch.

}
sathiamoorthy
  • 1,488
  • 1
  • 13
  • 23