source 는 Github 에 있습니다.
@Test
public void 전각문자테스트() throws Exception {
// 전각문자 공백 (0xA1 0xA1)
byte[] bytes = {(byte)0xA1, (byte)0xA1};
Assert.assertThat(bytes.length, is(2));
String s = new String(bytes, Charset.forName("euc-kr"));
// 2개의 바이트를 읽어서 하나의 전각문자로 만드니 길이가 1
Assert.assertThat(s.length(), is(1));
byte[] tmp = s.getBytes(Charset.forName("euc-kr"));
// 전각문자를 bytes 변환하면 1개의 전각문자는 2byte
Assert.assertThat(tmp.length, is(2));
}
/**
* 반각문자 --> 전각문자 변환
*
* @param s
* @return
*/
public static String toFullWidthCharacter(String s) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// 영문 알파벳 or 특수 문자
if (c >= 0x21 && c <= 0x7e) {
c += 0xfee0;
}
// 공백 (=space)
else if (c == 0x20) {
c = 0x3000;
}
sb.append(c);
}
return sb.toString();
}
/**
* 전각문자를 반각문자로 변환
* @param s
* @return
*/
public static String toHalfWidthCharacter(String s) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// 영문 알파벳 or 특수 문자
if (c >= '!' && c <= '~') {
c -= 0xfee0;
}
// 공백 (=space)
else if (c == ' ') {
c = 0x20;
}
sb.append(c);
}
return sb.toString();
}
@Test
public void 반각문자_전각문자_변환_테스트() throws Exception {
String s = " ";
// 반각문자 공백이기에 1bytes
Assert.assertThat(s.getBytes(Charset.forName("euc-kr")).length, is(1));
String fullWidthCharacter = StringUtils.toFullWidthCharacter(s);
// 전각문자 공백이기에 2bytes
Assert.assertThat(fullWidthCharacter.getBytes("euc-kr").length, is(2));
String halfWidthCharacter = StringUtils.toHalfWidthCharacter(fullWidthCharacter);
// 반각문자 bytes 이기에 byte 길이 1
Assert.assertThat(halfWidthCharacter.getBytes("euc-kr").length, is(1));
}