truncate string On Word Boundary - Android java.lang

Android examples for java.lang:String Algorithm

Description

truncate string On Word Boundary

Demo Code

import java.util.Arrays;

public class Main{

    public static String truncateOnWordBoundary(String string, int length,
            String appendString) {
        if (string.length() <= length)
            return string;

        char[] chars = string.toCharArray();
        StringBuffer buffer = new StringBuffer();
        String result = "";
        int lastWhitespace = 0;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == ' ')
                lastWhitespace = i;//ww  w . j  a v  a 2s .co m
            buffer.append(chars[i]);

            if (i >= length) {
                result = buffer.substring(0, lastWhitespace);
                break;
            }
        }
        return result + appendString;
    }

}

Related Tutorials