Created
February 28, 2013 15:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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