我有一根可能很长的绳子,需要巧妙地剪断它。下面的例子。
鉴于:
Very long string that is really too long to be placed on UI.
剪切以留下不超过N
字母的字符串:
Very long string that is really too...
这不应该拆分以下单词:
Very long string that is real...
有没有完整的解决方案/库?
我有一根可能很长的绳子,需要巧妙地剪断它。下面的例子。
鉴于:
Very long string that is really too long to be placed on UI.
剪切以留下不超过N
字母的字符串:
Very long string that is really too...
这不应该拆分以下单词:
Very long string that is real...
有没有完整的解决方案/库?
我会尝试类似的东西。
public static String truncate(String line, int maxLength) {
if(line.length() < maxLength) return line;
int pos = line.lastIndexOf(" ", maxLength-3);
if (pos <= 0) pos = maxLength - 3; // no spaces, so just cut anyway
return line.substring(0, pos) + "...";
}
您需要使用setEllipsize (TextUtils.TruncateAt where
)。在此处找到的文档。
您可以使用此类并调用其静态方法。此方法将防止越界错误和空指针异常
公共类 SmartSubstring {
public static String smartSubstring(String str, int maxLength) {
String subStr = str.substring(0);
if (maxLength == 0) {
return "";
} else if (str.length() <= maxLength) {
return str;
} else {
int i = maxLength;
while (i >= 0) {
while (str.length() < i) {
i--;
}
if (str.charAt(i) == ' ') {
subStr = str.substring(0, i);
break;
}
i--;
}
return subStr;
}
}
public static void main(String[] args) {
String test = new String("Otomotopia is a very very long word that is "
+ "hard to contain in a mobile application screen");
for (int i = 0; i < 200; i++) {
String tester = SmartSubstring.smartSubstring(test, i);
System.out.println(tester + tester.length());
}
}
}
您可以使用 StringTokenizer 通过使用空格的单词来分割字符串,然后只输出前几个单词。这个链接有一个很好的例子: http ://www.mkyong.com/java/java-stringtokenizer-example/