2008. 11. 20. 10:59
String 자르기!
2008. 11. 20. 10:59 in IT일반/Java
public class CutTest {
public static void main(String[] args) {
String str = "あいおうおあいおうおあいおうお";
String str1 = "abcdeabcdeabcdeabcde";
System.out.println(12 + ": [" + cutStringByBytes(str, 9) + "]");
System.out.println(12 + ": [" + cutStringByBytes(str1, 9) + "]");
}
public static String spaces(int count) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < count; i++) {
sb.append(" ");
}
return sb.toString();
}
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 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));
}
}