I found this algorithm from this post Objective-c Line breaks every 10 characters (Keeping words in tact) the problem is that it never returns the last word it always discards it somehow.
NSString *sourceStr = @"The Chocholate Experience in the Anna Ice Cream Museum - Spanish";
NSMutableString *resultString = [[NSMutableString alloc] init];
NSMutableString *currentLine = [[NSMutableString alloc] init];
NSMutableArray *stringsArray = [[NSMutableArray alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:sourceStr];
NSString *scannedString = nil;
while ([scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString: &scannedString]) {
if ([currentLine length] + [scannedString length] <= 23) {
[currentLine appendFormat:@"%@ ", scannedString];
}
else if ([currentLine length] == 0) { // Newline but next word > 23
[resultString appendFormat:@"%@\n", scannedString];
}
else { // Need to break line and start new one
[resultString appendFormat:@"%@\n", currentLine];
[currentLine setString:[NSString stringWithFormat:@"%@ ", scannedString]];
}
[scanner scanCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString:NULL];
}
NSLog(@"Result String: \n%@", resultString);
I get this as the output:
The Chocholate
Experience in the Anna
Ice Cream Museum -
gets rid of the last word which is Spanish. Anyone can see the bug? I've been at this for hours now. Any help would be greatly appreciated