May be you can separate with componentsSeparatedByCharactersInSet:
and re-construct lines.
But in your case, I think you'd better to iterate unichar
s.
NSMutableArray *result = [NSMutableArray array];
NSUInteger charCount = string.length;
unichar *chars = malloc(charCount*sizeof(unichar));
if(chars == NULL) {
return nil;
}
[string getCharacters:chars];
unichar *cursor = chars;
unichar *lineStart = chars;
unichar *wordStart = chars;
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
while(cursor < chars+charCount) {
if([whitespaces characterIsMember:*cursor]) {
if(cursor - lineStart >= length) {
NSString *line = [NSString stringWithCharacters:lineStart length:wordStart - lineStart];
[result addObject:line];
lineStart = wordStart;
}
wordStart = cursor + 1;
}
cursor ++;
}
if(lineStart < cursor) {
[result addObject:[NSString stringWithCharacters:lineStart length: cursor - lineStart]];
}
free(chars);
return result;
Input:
@"I would like to make this only split the string on a space. So, if the last character of the substring is not a space, I would like it it shorten that substring until the last character is a space (hopefully that makes sense). Basically I want this to split the string, but not split words in the process."
Output(length == 30):
(
"I would like to make this ",
"only split the string on a ",
"space. So, if the last ",
"character of the substring is ",
"not a space, I would like it ",
"it shorten that substring ",
"until the last character is a ",
"space (hopefully that makes ",
"sense). Basically I want this ",
"to split the string, but not ",
"split words in the process."
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…