如果我有一个字符串要加载到TextField中,我如何使换行每隔10个字符出现一次(包括空格等),但不转到单词中间的下一行。。。喜欢用最多10个字符包装文本吗?但我不仅仅是在UITextField中包装,我实际上需要输入,因为它也将用于其他内容。。。(如果这很重要的话,这是iOS版的)任何帮助都很感激,我真的很困!
您可能想在循环中使用NSScanner来组合这类东西,但要找出精确的算法,您需要明确它的工作方式。以下是您需要回答的问题:
- 为了包装文本,单词之间一个以上空白的序列应该"折叠"成一个空白吗?还是应该将5个连续空白的序列算作5个字符,而每行10个字符?我假设您希望折叠而不是保留多个空间
- 如果你有一个超过10个字符的单词,你希望它如何工作?你希望它以一行超过10个字符结束,还是希望插入换行符并在这种情况下强制换行?我假设您希望允许长度超过10个字符的单词扩展到10个字符之外
考虑到这些关于你的问题的假设,我会这样编码:
NSMutableString *resultString = [[NSMutableString alloc] init];
NSMutableString *currentLine = [[NSMutableString alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:sourceString];
NSString *scannedString = nil;
while ([scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString: &scannedString]) {
if ([currentLine length] + [scannedString length] <= 10) {
[currentLine appendFormat:@"%@ ", scannedString];
}
else if ([currentLine length] == 0) { // Newline but next word > 10
[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];
}
我创建了一个实际上可以打断的东西,不是每10个字符,而是在单词之间,不是没有连字符引擎,这需要一个字典。我把它建立在感知答案的基础上。
NSMutableString * guid = [NSMutableString stringWithString: @"Some suitably long string will be used for demonstration purposes"];
int lastSpace=0;
int lastbreak=0;
NSUInteger i = [guid length];
while(i > 0) {
if ([guid characterAtIndex:i-1]==' ')
lastSpace=i;
lastbreak++;
if (lastbreak>9) {
if (lastSpace!=0) {
[guid insertString:@"n" atIndex: lastSpace];
} else {
// we have not found a space in 10 chars, so break where there is no space.
// no H&J engine here, so we can add the - or not.
[guid insertString:@"-n" atIndex: i];
i++; // since were adding a character, dont skip a character.
}
lastbreak=0;
lastSpace=0;
}
i--;
}
我会用这样的方式来做:
NSString *finalString = @"";
NSString *yourString = @"This is your very very long string with many words and letters and spaces, haha";
NSArray *someArray = [yourString componentsSeparatedByString:@" "]; //that will make an array with strings separated by spaces
for (int i = 0; i < [someArray count]; i++) {
NSArray *someArray2 = [finalString componentsSeparatedByString:@"n"];
if ([[someArray objectAtIndex:i]length] + [[someArray2 lastObject]length] > 9 )
finalString = [NSString stringWithFormat:@"%@n%@", finalString, [someArray objectAtIndex:i]];
else
finalString = [NSString stringWithFormat:@"%@ %@", finalString, [someArray objectAtIndex:i]];
}
我相信这样的事情应该奏效。我附近没有Mac,所以我记下了我的记忆(这并不总是完美的)。因此,代码中可能存在一些错误。
希望它能帮助
您必须自己将换行符插入字符串中,这个afaik没有内置函数。
NSMutableString * guid = [NSMutableString stringWithString: @"Some suitably long string will be used for demonstration purposes"];
for(NSUInteger i = 10; i < [guid length] ; i += 10) {
[guid insertString:@"n" atIndex: i];
}
NSLog(@"GUID: %@", guid);