views:

472

answers:

1

I have an NSString I'm working with, but I would like to parse it by character length. So break it apart into an NSArray, and have each object in the array be x characters from that string. So basically, break up the string into sub strings of a certain length

So, how do I do it?

example:

NSString *string = @"Here is my string"

NSArray objects:

"Her"

"e i"

"s m"

"y s"

"tri"

"ng"

+4  A: 

Can this work? Not tested though

@interface NSString (MyStringExtensions)
- (NSArray*)splitIntoPartsWithLength:(NSUInteger)length;
@end

@implementation NSString (MyStringExtensions)
- (NSArray*)splitIntoPartsWithLength:(NSUInteger)length
{
    NSRange range = NSMakeRange(0, length);
    NSMutableArray *array = [NSMutableArray array];
    NSUInteger count = [self length];

    while (length > 0) {
        if (range.location+length >= count) {
            [array addObject:[self substringFromIndex:range.location]];
            return [NSArray arrayWithArray:array];
        }
        [array addObject:[self substringWithRange:range]];
        range.location = range.location + length;
    }
    return nil;
} 
@end

EDIT -- implemented as a category use as

NSString *myString = @"Wish you a merry x-mas";
NSArray *array = [myString splitIntoPartsWithLength:10];
epatel
so this will let me parse the string into pieces x characters long?What do I do, just modify the int length to the length I want?
Matt S.
It's a method, so you would specify the length when sending yourself this `splitString:intoPartLengths:` message.
Peter Hosey
epatel: You never decrease the value of `length`, so that `while` loop will loop forever.
Peter Hosey
Peter: He'll get into the if statement eventually and exit the while loop there. I don't find it the easiest to follow code, but it should work.
Johan Kool
Ok, I'm getting there, but I'm getting the error "unrecognized selector sent to instance 0xd21920" when I run it
Matt S.
matt: Did you add the method to the class that that instance is an instance of? You need to do that.
Peter Hosey
yea. I'm calling it with [array splitString:string intoPartLengths:10];(array and string are created earlier in my code)
Matt S.
Thank you SO much, it works!!!!!
Matt S.