Java 截断最近单词边界上的字符串
是否可以将Java字符串截断到多个字符后最接近的单词边界。与PHP wordwrap()函数类似,如图所示。使用Java 截断最近单词边界上的字符串,java,string,Java,String,是否可以将Java字符串截断到多个字符后最接近的单词边界。与PHP wordwrap()函数类似,如图所示。使用java.text.BreakIterator,类似如下: String s = ...; int number_chars = ...; BreakIterator bi = BreakIterator.getWordInstance(); bi.setText(s); int first_after = bi.following(number_chars); // to trunc
java.text.BreakIterator
,类似如下:
String s = ...;
int number_chars = ...;
BreakIterator bi = BreakIterator.getWordInstance();
bi.setText(s);
int first_after = bi.following(number_chars);
// to truncate:
s = s.substring(0, first_after);
可以使用正则表达式
Matcher m = Pattern.compile("^.{0,10}\\b").matches(str);
m.find();
String first10char = m.group(0);
使用第一种方法,最终的长度将大于number_chars。如果您需要一个确切的最大值或更小的值,比如Twitter消息,请参阅下面的我的实现 请注意,regexp方法使用空格来分隔单词,而BreakIterator则会分隔单词,即使它们有逗号和其他字符。这是更可取的 以下是我的全部功能:
/**
* Truncate text to the nearest word, up to a maximum length specified.
*
* @param text
* @param maxLength
* @return
*/
private String truncateText(String text, int maxLength) {
if(text != null && text.length() > maxLength) {
BreakIterator bi = BreakIterator.getWordInstance();
bi.setText(text);
if(bi.isBoundary(maxLength-1)) {
return text.substring(0, maxLength-2);
} else {
int preceding = bi.preceding(maxLength-1);
return text.substring(0, preceding-1);
}
} else {
return text;
}
}
使用
BreakIterator
的解决方案在将句子分解为URL时并不是很简单,它分解URL的方式不是很好。我宁愿使用我的解决方案:
public static String truncateText(String text, int maxLength) {
if (text != null && text.length() < maxLength) {
return text;
}
List<String> words = Splitter.on(" ").splitToList(text);
List<String> truncated = new ArrayList<>();
int totalCount = 0;
for (String word : words) {
int wordLength = word.length();
if (totalCount + 1 + wordLength > maxLength) { // +1 because of space
break;
}
totalCount += 1; // space
totalCount += wordLength;
truncated.add(word);
}
String truncResult = Joiner.on(" ").join(truncated);
return truncResult + " ...";
}
public静态字符串truncateText(字符串文本,int-maxLength){
if(text!=null&&text.length()maxLength){/+1,因为有空格
打破
}
totalCount+=1;//空格
totalCount+=字长;
截断。添加(word);
}
字符串truncResult=Joiner.on(“”).join(截断);
返回truncResult+“…”;
}
Splitter/Joiner来自番石榴。我还在使用cas的末尾添加了
…
。这非常感谢,尽管aa bi.truncateAt()是否要求太多?:)确保您测试的number_chars不大于s.length(),否则会出现异常。仅供参考,我试图编辑java以反映这一事实,但编辑被拒绝。