Java String Sub String substringByByteCount(String str, int byteCount)

Here you can find the source of substringByByteCount(String str, int byteCount)

Description

substring By Byte Count

License

Open Source License

Declaration

public static String substringByByteCount(String str, int byteCount) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static String substringByByteCount(String str, int byteCount) {
        byte[] bytes = str.getBytes();
        if (bytes.length <= byteCount) {
            return str;
        }//from w  w w.j ava  2  s  .com
        int strIndex = 0;
        for (int i = 0; i < bytes.length;) {
            int len = utf8Len(bytes[i]);
            if (i + len <= byteCount) {
                i += len;
                strIndex++;
            } else {
                break;
            }
        }
        return str.substring(0, strIndex);
    }

    public static int utf8Len(byte b) {
        int num = b & 255;
        if (num < 0x80)
            return 1;
        if (num < 0xe0)
            return 2;
        if (num < 0xf0)
            return 3;
        if (num < 0xf8)
            return 4;
        return 5;
    }
}

Related

  1. substringBetween(String str, String tag)
  2. substringBetween(String str, String tag)
  3. substringBetweenStrings(String within, String pre, String post)
  4. subStringByByte(String orignal, int subcount)
  5. subStringByByte(String str, int byteLenth)
  6. subStringByBytes(String str, int toCount, String more)
  7. substringByCodePoint(String inputStr, int codePointStart, int codePointEnd)
  8. substringByMask(String baseString, String baseMask, String subMask)
  9. subStringByte(String str, int toCount, String more)