Skip to content

Instantly share code, notes, and snippets.

@carbamide
Created February 28, 2013 15:49
Show Gist options
  • Save carbamide/5057702 to your computer and use it in GitHub Desktop.
Save carbamide/5057702 to your computer and use it in GitHub Desktop.
Split a long string into an array with a given max number of characters
+(NSArray *)splitString:(NSString *)str maxCharacters:(NSInteger)maxLength
{
NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:1];
NSArray *wordArray = [str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSInteger numberOfWords = [wordArray count];
NSInteger index = 0;
NSInteger lengthOfNextWord = 0;
while (index < numberOfWords) {
NSMutableString *line = [NSMutableString stringWithCapacity:1];
while ((([line length] + lengthOfNextWord + 1) <= maxLength) && (index < numberOfWords)) {
lengthOfNextWord = [[wordArray objectAtIndex:index] length];
[line appendString:[wordArray objectAtIndex:index]];
index++;
if (index < numberOfWords) {
[line appendString:@" "];
}
}
[tempArray addObject:line];
}
return tempArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment