시소당
이것은 자를 길이를 리턴하는 것이 아니고 절단된 스트링을 리턴합니다.
속도를 빠르게 하기 위해 변환된 바이트 배열에서
파라미터로 넘어온 길이(length)를 기준으로 그 좌측으로
각 바이트들의 MSB(최상위 비트)가 1인지 아닌지 체크해 나갑니다.
cutStringByBytes 메소든 파라미터로 지정한 길이 혹은 거기에 +1 한 것이 되게 잘라 리턴하는 메소드이고,
cutInStringByBytes 메소든 파라미터로 지정한 길이 혹은 거기에 -1 한 것이 되게 잘라 리턴하는 메소드입니다.
+1 또는 -1을 하는 이유는 잘단된 마지막 바이트가
한글 한 자의 2 바이트가 잘려 선두 바이트만 남는 경우를
방지하기 위함입니다.
public class CutStringTest {
/**
* 만든 이: 자바클루(javaclue)
* 만든 날: 2003/05/15
*
* 지정한 정수의 개수 만큼 빈칸(" ")을 스트링을 구한다.
*
* @param int 문자 개수
* @return String 지정된 개수 만큼의 빈칸들로 연결된 String
*/
public static String spaces(int count) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < count; i++) {
sb.append(' ');
}
return sb.toString();
}
/**
* 만든 이: 자바클루(javaclue)
* 만든 날: 2003/06/26
*
* 지정한 정수의 개수 만큼 빈칸(" ")을 스트링을 구한다.
* 절단된 String의 바이트 수가 자를 바이트 개수보다 모자라지 않도록 한다.
*
* @param str 원본 String
* @param int 자를 바이트 개수
* @return String 절단된 String
*/
public static String cutStringByBytes(String str, int length) {
byte[] bytes = str.getBytes();
int len = bytes.length;
int counter = 0;
if (length >= len) {
return str + spaces(length - len);
}
for (int i = length - 1; i >= 0; i--) {
if (((int)bytes[i] & 0x80) != 0)
counter++;
}
return new String(bytes, 0, length + (counter % 2));
}
/**
* 만든 이: 자바클루(javaclue)
* 만든 날: 2003/06/26
*
* 지정한 정수의 개수 만큼 빈칸(" ")을 스트링을 구한다.
* 절단된 String의 바이트 수가 자를 바이트 개수를 넘지 않도록 한다.
*
* @param str 원본 String
* @param int 자를 바이트 개수
* @return String 절단된 String
*/
public static String cutInStringByBytes(String str, int length) {
byte[] bytes = str.getBytes();
int len = bytes.length;
int counter = 0;
if (length >= len) {
return str + spaces(length - len);
}
for (int i = length - 1; i >= 0; i--) {
if (((int)bytes[i] & 0x80) != 0)
counter++;
}
return new String(bytes, 0, length - (counter % 2));
}
public static void main(String[] args) {
String str = "자바클루(javaclue)가 만든 글자 자르기";
for (int i = 4; i < 24; i++)
System.out.println(i + ": [" + cutInStringByBytes(str, i) + "]");
}
}
[출처] [JAVA] 한글과 영문을 같은 길이로 자르기. |작성자 레인보우
http://blog.naver.com/jeany4u/20003783898