Java String Truncate truncate(String text, int size, String charsetName)

Here you can find the source of truncate(String text, int size, String charsetName)

Description

truncate

License

Open Source License

Declaration

public static String truncate(String text, int size, String charsetName) 

Method Source Code

//package com.java2s;

public class Main {

    public static String truncate(String text, int size) {
        return truncate(text, size, "UTF-8");
    }/*from   w  ww  .  ja va 2s.  com*/

    public static String truncate(String text, int size, String charsetName) {
        return truncate(text, 0, size, charsetName, 3);
    }

    public static String truncate(String text, int start, int size, String charsetName) {
        return truncate(text, start, size, charsetName, 3);
    }

    public static String truncate(String text, int start, int size, String charsetName, int charBytes) {
        if (text == null) {
            return "";
        }

        int count = 0;
        StringBuilder stxt = new StringBuilder(size);

        char[] chars = text.toCharArray();
        for (int i = start; (i < chars.length && size > count); i++) {
            try {
                String s = String.valueOf(chars[i]);
                count += s.getBytes(charsetName).length;
            } catch (Exception e) {
                count += charBytes;
            }

            if (count <= size) {
                stxt.append(chars[i]);
            }
        }

        return stxt.toString();
    }
}

Related

  1. truncate(String text)
  2. truncate(String text, int len)
  3. truncate(String text, int length)
  4. truncate(String text, int length)
  5. truncate(String text, int maxLength)
  6. truncate(String text, int truncatedLength)
  7. truncate(String toTruncate, int maxSize)
  8. truncate(String url, int offset, int size)
  9. Truncate(String v, int length)