我正在使用此问题(https://stackoverflow.com/a/13854813)的答案,根据特定长度将大字符串拆分为数组。
- (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;
}
我想让它只拆分空格上的字符串。所以,如果子串的最后一个字符不是空格,我希望它缩短子字符串直到最后一个字符是一个空格(希望这是有意义的)。基本上我想要分割字符串,但不要在过程中拆分。
有什么建议吗?
答案 0 :(得分:0)
可能您可以与componentsSeparatedByCharactersInSet:
分开并重新构建行。
但在你的情况下,我认为你最好迭代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;
输入:
@"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."
)