limit String length with BreakIterator - Java java.lang

Java examples for java.lang:char

Description

limit String length with BreakIterator

Demo Code


//package com.java2s;

import java.text.BreakIterator;

public class Main {
    public static void main(String[] argv) throws Exception {
        String value = "java2s.com";
        Integer length = 2;// w w w. j  a v  a2  s .  c  om
        System.out.println(limit(value, length));
    }

    public static String limit(String value, Integer length) {
        if (value == null || value.length() <= length)
            return value;
        String s = value;
        int number_chars = length;
        BreakIterator bi = BreakIterator.getWordInstance();
        bi.setText(s);
        int first_after = bi.following(number_chars);
        // to truncate:
        s = s.substring(0, first_after).concat("...");
        return s;
    }
}

Related Tutorials