Cocoa: Parse NSString by character length
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, h开发者_Go百科ow do I do it?
example:
NSString *string = @"Here is my string"
NSArray objects:
"Her"
"e i"
"s m"
"y s"
"tri"
"ng"
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];
精彩评论