Вопрос

I'm trying to split an NSString into multiple NSString's. One new string for every character in the NSString. Is there a simpler way to do this than just doing it manually? A method or API that can do this automatically?

For example, turn this string:

_line1 = [NSString stringWithFormat:@"start"];

into:

_string1 = [NSString stringWithFormat:@"s"];
_string2 = [NSString stringWithFormat:@"t"];
_string3 = [NSString stringWithFormat:@"a"];
_string4 = [NSString stringWithFormat:@"r"];
_string5 = [NSString stringWithFormat:@"t"];
Это было полезно?

Решение 2

First off, why are you using _line1? You should never access properties directly via their pointer. Please use self.line1 instead. I will assume you have @property NSString *line1; in your class definition. If not, you'll need to adjust the code I'm posting as necessary.

Second, no there's no way built in. But it's pretty simple to do manually:

NSMutableArray *chars = [NSMutableArray array];
NSUinteger i = 0;
for (i = 0; i < self.line1.length; i++) {
  [chars addObject:[self.line1 substringWithRange:NSMakeRange(i, 1)]];
}

Другие советы

The documentation out there is really good. There are lots of ways you could do this.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html

One way is to make an array of NSStrings that contain each character.

NSString * line1 = @"start";
NSMutableArray * characters = [NSMutableArray array];

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

// Then loop over characters array ... 
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top