我有一个长度为1000-1500个字符的字符串。我想将其分为几段。我现在正在做的是:
String tempDisplayText =
"this is the long...... string of length 1000-2000 chars";
String displayText = null;
if (tempDisplayText != null && tempDisplayText.length() > 400) {
int firstFullStopIndex = tempDisplayText.indexOf(". ", 350);
if (firstFullStopIndex > 0) {
displayText = "<p>"
+ tempDisplayText.substring(0, firstFullStopIndex)
+ ".</p><p>"
+ tempDisplayText.substring(firstFullStopIndex + 1)
+ "</p>";
feed.setDisplayText(displayText);
}
}
这段代码可以正常工作,但是将整个字符串仅分为2个段落。但是有时下一段过长,因此失去了可读性。在Java中,是否有任何标准的方法可以将字符串分成段落?
我认为没有理由不应该在其余部分(即第二段)中重复这一步骤。你不能拆分一个句子。
StringBuilder sb = new StringBuilder();
if (tempDisplayText != null) {
int firstFullStopIndex;
while( tempDisplayText.length() > 400
&&
(firstFullStopIndex = tempDisplayText.indexOf(". ", 350)) >= 0 ){
sb.append( "<p>" );
sb.append( tempDisplayText.substring(0, firstFullStopIndex) );
sb.append( ".</p>" );
tempDisplayText = tempDisplayText.substring(firstFullStopIndex + 1);
}
if( tempDisplayText.length() > 0 ){
sb.append( "<p>" ).append( tempDisplayText ).append( "</p>" );
}
tempDisplayText = sb.toString();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句