IT분야/Java
[JAVA]java 한글 자르기
suroMind
2013. 2. 26. 12:33
출처 : http://pmguda.com/579
여러 메소드를 사용해 봤지만 아래 메소드는 잘되네요.
단 UTF-8환경에서만 테스트 해봤습니다.
인코딩 환경에 따라 다르다고 하는데 일단 되니깐 패스..
public String subStringBytes(String str, int byteLength) {
// String 을 byte 길이 만큼 자르기.
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 + 2) {
tempSize += 2;
retLength++;
} else {
return str.substring(0, retLength) + "...";
}
} else {
if (byteLength > tempSize) {
tempSize++;
retLength++;
}
}
}
return str.substring(0, retLength);
}