본문 바로가기

IT/JAVA

java 한글 byte로 깨짐없이 자르기

public String subStringBytes(String str, int byteLength, int sizePerLetter) {
  int retLength = 0;
  int tempSize = 0;
  int asc;
  if (str == null || "".equals(str) || "null".equals(str)) {
    str = "";
  }
 
  int length = str.length();
 
  for (int i = 1; i <= length; i++) {
    asc = (int) str.charAt(i - 1);
    if (asc > 127) {
      if (byteLength >= tempSize + sizePerLetter) {
        tempSize += sizePerLetter;
        retLength++;
      }
    } else {
      if (byteLength > tempSize) {
        tempSize++;
        retLength++;
      }
    }
  }
 
  return str.substring(0, retLength);
}


UTF-8일 경우

subStringBytes("블라블라블라라", 10, 3);

EUC-KR일 경우

subStringBytes("블라블라블라라", 10, 2);



출처: http://www.donnert.net/88 [donnert.net]

'IT > JAVA' 카테고리의 다른 글

URL에서 정보 가져오기  (0) 2017.08.02
HashMap 정렬  (0) 2016.03.11
JAVA 특수문자 split  (0) 2015.11.05
랜덤숫자 7개 생성하기 (로또번호 생성하기,정렬)  (0) 2014.12.29
이클립스 루나 테마,배경 바꾸기 ( DARK )  (0) 2014.07.10