如何包装一个字符串

时间:2012-06-12 05:22:51

标签: java string

我有一个非常长的字符串,如“移动事件”,它们可以是任意长度的字符串,我想显示....在说出一定长度之后,该怎么做?

6 个答案:

答案 0 :(得分:4)

使用Apache Common库的WordUtils类。

static String wrap(java.lang.String str, 
       int wrapLength, java.lang.String newLineStr, boolean wrapLongWords)  

示例 -

    String str = "This is a sentence that we're using to test the wrap method";
    System.out.println("Original String 1:\n" + str);
    System.out.println("\nWrap length of 10:\n" + WordUtils.wrap(str, 10));
    System.out.println("\nWrap length of 20:\n" + WordUtils.wrap(str, 20));
    System.out.println("\nWrap length of 30:\n" + WordUtils.wrap(str, 30));

答案 1 :(得分:3)

你可以这样做 -

    String str = "The event for mobile is here";
    String temp = "";
    if(str !=null && str.length() > 10) {
        temp = str.substring(0, 10) + "...."; // here 0 is start index and 10 is last index
    } else {
        temp = str;
    }
    System.out.println(temp);

输出将是 - 事件......

答案 2 :(得分:1)

String template = "Hello I Am A Very Long String";
System.out.println(template.length() > 10 ? template.substring(0, 10) + "..." : template);

您只需查看长度,然后执行substring

或者,如果您可以使用Apache的常用Util,请使用此WordUtils.wrap()

我之前没有做过很好的搜索,this SO Post正是你想要的

答案 3 :(得分:1)

如果您想要完整的单词,请执行以下操作:

public static void shortenStringFullWords(String str, int maxLength) {
    StringBuilder output = new StringBuilder();
    String[] tokens = str.split(" ");
    for (String token: tokens) {
        if (output.length() + token.length <= maxLength - 3) {
            output.append(token);
            output.append(" ");
        } else {
            return output.toString().trim() + "...";
        }
    }
    return output.toString().trim();
}

答案 4 :(得分:1)

你可以这样做

    String longString = "lorem ipusum ver long string";
    String shortString = "";
    int maxLength = 5;
    if(longString != null && longString.length() > maxLength) {
        shortString = longString.substring(0,maxLength - 1)+"...";
    }

在这里,您可以将maxLength更改为所需的数字。

答案 5 :(得分:1)

String myString ="my lengthy string";
    int startIndex=0, endIndex=myString.length(), lengthLimit = 10;



    while(startIndex<endIndex) {
        System.out.println(myString.substring(startIndex,  startIndex+lengthLimit));
        startIndex = startIndex+lengthLimit+1;
    }