切长串

时间:2013-06-07 22:05:47

标签: java

我有一个很长的字符串,需要聪明地剪掉它。示例如下。
给出:

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...

有没有完整的解决方案/库?

4 个答案:

答案 0 :(得分:4)

我会尝试类似的东西。

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) + "...";
}

答案 1 :(得分:3)

您需要使用setEllipsize (TextUtils.TruncateAt where)。找到文档here

答案 2 :(得分:0)

您可以使用StringTokenizer通过使用空格的单词剪切字符串,然后输出前几个单词。这个链接有一个很好的例子: http://www.mkyong.com/java/java-stringtokenizer-example/

答案 3 :(得分:0)

您可以使用此类并调用其静态方法。此方法将防止outofbounds错误和空指针异常

public class 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());
    }
}
}