2012-12-09 42 views
0

我找到了一個這樣做的類,它看起來正是我需要的。在Java中添加字符串並添加「...」

public static class StringUtil 
{ 
    public static String limit(String value, int length) 
    { 
    StringBuilder buf = new StringBuilder(value); 
    if (buf.length() > length) 
    { 
     buf.setLength(length); 
     buf.append("…"); 
    } 

    return buf.toString(); 
    } 
} 

我有一個名爲review字符串,我用這個類是這樣的:

StringUtil.limit(review, 50); 

它似乎並沒有被追加。

這是值得的,它是一個Android應用程序。這是在ListFragement內的AsyncTaskPostExectute方法中完成的。

我正在做這個對嗎?

回答

1

您發送的字符串(評論)是否超過50個字符?請注意,該功能只會在結果長於極限時修改結果。

您似乎也不接受該方法的返回值。此方法不會修改參數值(因爲它不能),它會返回一個帶有新值的NEW String。

嘗試

String newreview = StringUtil.limit(review, 50); 
System.out.println(newreview); 

好吧,你自找的修改要到下一個空格第一。我沒有編譯這個,但它應該接近。

public static String limit(String value, int length) 
    { 
    // note to Test this first, so you don't create a Buffer unnecessarily. 
    String ret = value; 
    if (value.length() > length) { 
     StringBuilder buf = new StringBuilder(value); 
     buf.setLength(length); 
     int cur = length; 
     while(cur < value.length() && value.charAt(cur) != ' ') { 
      buf.append(value.charAt(cur)); 
     } 
     if (cur == value.length()) { 
      ret = value; // we copied the whole string, as it turns out. 
     } else { 
      buf.append("..."); 
      ret = buf.toString(); 
     } 
    } 
    return value; 
    } 
+1

另請注意,它會在限制後附加elipses,所以您實際上會得到一個長度爲53個字符的字符串。 – billjamesdev

+0

你說得對,我需要從新的結果中創造價值。標記正確....再次感謝。 – KickingLettuce

+0

獎勵問題:我正在截斷句子,但不想削減單詞,我可以添加什麼東西,它只停留在下一個空間嗎? – KickingLettuce

0
public static String limit(String value, int length) 
    { 
    return value+"..."; 
    } 
+0

該代碼已經很好了,因爲它是。問題是另一個。 – kiamlaluno