[英]How to frame Paragraph into multiple lines of 60 Characters
我是编码领域的新手,对于这个问题以前可能曾经提出过,我深表歉意。 我正在努力实现这样的目标。 假设我有一个这样的段落或行,超过64个字符,而I've been using the Lumia 822 for over a month now and I noticed that the moment I reach over 70 characters
在第60个字符处,我们注意到了单词,因此应将其推到下一行。 预期的输出。
I've been using the Lumia 822 for over a month now and I noticed that the moment I reach over 70 characters
您能帮我解决这个问题吗? 我用过String Tokenizer和substr(),但是没有用。
请提出您的宝贵建议。
谢谢。
一个非常简单的解决方案:
public String appendNewLine(String text, int max) {
int count = 0;
StringBuilder output = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (count >= max && c == ' ') {
count = 0;
output.append("\n");
} else {
output.append(c);
}
count++;
}
return output.toString();
}
此代码将确保每行严格小于或等于splitLen
。 之后的所有单词将移至下一行。
您可以使用splitLen
参数调整线宽。 我试图介绍几种情况。 如果缺少任何内容,请指出。
public String splitString(String s, int splitLen){
StringBuilder sb = new StringBuilder();
int splitStart = 0;
while(splitStart < s.length()){
int splitEnd = splitStart + splitLen;
splitEnd = splitEnd > s.length() ? s.length() : splitEnd; // avoid overflow
int spaceIndex = s.substring(splitStart, splitEnd)
.lastIndexOf(" ");
// look for lasts space in line, except for last line
if(spaceIndex != -1 && splitEnd != s.length()){
splitEnd = splitStart + spaceIndex;
}
// else (no space in line), split word in two lines..
sb.append(s.substring(splitStart, splitEnd))
.append(System.lineSeparator());
// if ends with space, skip space in next line
splitStart = splitEnd + (spaceIndex != -1 ? 1 : 0);
}
return(sb.toString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.