-2

I am trying to get each letter of an NSString using this line of code:

NSArray *array = [string componentsSeparatedByString:@""];
//string is equal to Jake
NSLog(@"Array Count:%d",[array count]);

I am expecting to get each letter of the word "Jake" but instead I am getting the whole word. Why?

Abdullah Shafique
  • 6,878
  • 8
  • 35
  • 70

2 Answers2

1

From Apple's Doc about this method

NSString *list = @"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:@", "];
produces an array { @"Norman", @"Stanley", @"Fletcher" }.

So empty separator will not separate each character of string, this method doesn't work this way.

Here is an answer for your question

How to convert NSString to NSArray with characters one by one in Objective-C

Community
  • 1
  • 1
B.S.
  • 21,660
  • 14
  • 87
  • 109
1

The idea of separating a string by nothing doesn't logically make sense, it is like trying to divide by zero. But to answer the question:

NSMutableArray *stringComponents = [NSMutableArray arrayWithCapacity:[string length]];
for (int i = 0; i < [string length]; i++) {
    NSString *character = [NSString stringWithFormat:@"%c", [string characterAtIndex:i]];
    [stringComponents addObject:character];
}`
Kevin
  • 16,696
  • 7
  • 51
  • 68
  • 2
    FYI - this will fail for any character with a Unicode value of `\U10000` or greater. – rmaddy Sep 07 '13 at 18:19
  • And one other issue, using `%c` instead of `%C` will make this code have problems for any non-ASCII character. – rmaddy Sep 07 '13 at 18:21