拆分string由一个常数,只在一个空格

我正在使用这个问题的答案( https://stackoverflow.com/a/13854813 )根据特定的长度将一个大的string拆分成一个数组。

- (NSArray *) componentSaparetedByLength:(NSUInteger) length{ NSMutableArray *array = [NSMutableArray new]; NSRange range = NSMakeRange(0, length); NSString *subString = nil; while (range.location + range.length <= self.length) { subString = [self substringWithRange:range]; [array addObject:subString]; //Edit range.location = range.length + range.location; //Edit range.length = length; } if(range.location<self.length){ subString = [self substringFromIndex:range.location]; [array addObject:subString]; } return array; } 

我想这只是把一个空格上的string分开。 所以,如果子string的最后一个字符不是空格,我希望它缩短子string,直到最后一个字符是一个空格(希望是有道理的)。 基本上我希望这个拆分string,但不能拆分过程中的单词。

有什么build议么?

也许你可以用componentsSeparatedByCharactersInSet:分开componentsSeparatedByCharactersInSet:重新构build行。

但就你而言,我认为你最好重复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." 

输出(长度== 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." )