Question

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"

Was it helpful?

Solution

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];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top