Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim String in Java while preserve full word

I need to trim a String in java so that:

The quick brown fox jumps over the laz dog.

becomes

The quick brown...

In the example above, I'm trimming to 12 characters. If I just use substring I would get:

The quick br...

I already have a method for doing this using substring, but I wanted to know what is the fastest (most efficient) way to do this because a page may have many trim operations.

The only way I can think off is to split the string on spaces and put it back together until its length passes the given length. Is there an other way? Perhaps a more efficient way in which I can use the same method to do a "soft" trim where I preserve the last word (as shown in the example above) and a hard trim which is pretty much a substring.

Thanks,

like image 296
AMZFR Avatar asked Oct 12 '11 09:10

AMZFR


1 Answers

Please try following code:

private String trim(String src, int size) {
    if (src.length() <= size) return src;
    int pos = src.lastIndexOf(" ", size - 3);
    if (pos < 0) return src.substring(0, size);
    return src.substring(0, pos) + "...";
}
like image 189
Tran Dinh Thoai Avatar answered Oct 06 '22 00:10

Tran Dinh Thoai