Java String Truncate truncateWhenUTF8(final String s, final int maxBytes)

Here you can find the source of truncateWhenUTF8(final String s, final int maxBytes)

Description

truncate When UTF

License

Open Source License

Declaration

public static String truncateWhenUTF8(final String s, final int maxBytes) 

Method Source Code

//package com.java2s;

public class Main {
    public static String truncateWhenUTF8(final String s, final int maxBytes) {
        int b = 0;
        for (int i = 0; i < s.length(); i++) {
            final char c = s.charAt(i);

            // ranges from http://en.wikipedia.org/wiki/UTF-8
            int skip = 0;
            int more;
            if (c <= 0x007f) {
                more = 1;/*from  www .  ja v  a 2 s .c o m*/
            } else if (c <= 0x07FF) {
                more = 2;
            } else if (c <= 0xd7ff) {
                more = 3;
            } else if (c <= 0xDFFF) {
                // surrogate area, consume next char as well
                more = 4;
                skip = 1;
            } else {
                more = 3;
            }

            if (b + more > maxBytes) {
                return s.substring(0, i);
            }
            b += more;
            i += skip;
        }
        return s;
    }
}

Related

  1. truncateType(String type)
  2. truncateUri(String uri)
  3. truncateUrl(String url)
  4. TruncateUrlPage(String strURL)
  5. truncateValue(String value, int limit, String endChars)
  6. truncateWhiteSpace(int len, int tabSize, String indentStr)
  7. truncateWithDefault(String value, int size, String defaultValue)
  8. truncateWithEllipsis(String str, int maxLength)
  9. truncAtWord(String a_text, int a_length)