Get sub String By Byte - Android java.lang

Android examples for java.lang:String Substring

Description

Get sub String By Byte

Demo Code

public class Main {

  public static String subStringByByte(String str, int startPos, int length) {
    if (str == null || str.length() == 0) {
      return "";
    }/*from  w  w w .  j  av  a  2s . co  m*/

    StringBuffer sb = new StringBuffer();
    int byteLen = 0;
    for (int i = 0; i < str.length(); i++) {
      int ascii = Character.codePointAt(str, i);
      if (ascii >= 0 && ascii <= 255) {
        byteLen++;
      } else {
        byteLen += 2;
      }
      if (byteLen >= startPos + 1 && byteLen <= length) {
        sb.append(str.charAt(i));
      } else {
        break;
      }
    }
    return sb.toString();
  }

}

Related Tutorials