「Java入門」半角数字を全角数字に変換するサンプル

Javaコード
public class Hankaku2Zenkaku {

/**
* 全角数字を半角数字に変換
*
* @param str
*/
public static String full2Half(String strDigit) {
if (strDigit == null) {
throw new IllegalArgumentException();
}
StringBuffer sb = new StringBuffer(strDigit);
for (int i = 0; i < strDigit.length(); i++) {
char c = strDigit.charAt(i);
if ('0’ <= c && c <= '9’) {
sb.setCharAt(i, (char) (c – '0’ + '0’));
}
}
return sb.toString();
}

/**
* 半角数字を全角数字に変換
*
* @param str
*/
public static String half2Full(String strDigit) {
if (strDigit == null) {
throw new IllegalArgumentException();
}
StringBuffer sb = new StringBuffer(strDigit);
for (int i = 0; i < strDigit.length(); i++) {
char c = strDigit.charAt(i);
if ('0’ <= c && c <= '9’) {
sb.setCharAt(i, (char) (c – '0’ + '0’));
}
}
return sb.toString();
}

public static void main(String[] args) {

String aa = half2Full(“123456");
System.out.println(“結果1:" + aa);
String bb = full2Half(“98755");
System.out.println(“結果2:" + bb);
}

}

Java

Posted by arkgame