「Java開発」文字列の半角/全角を相互変換するサンプル

2018年3月2日

サンプルコード
public class HalfToFullDemo {

/**
* 半角を全角に変換
*
* @param strTarget
* String.
* @return 全角文字列.
*/
public static String HalfToFull(String strTarget) {
char c[] = strTarget.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == ' ') {
c[i] = '\u3000’;
} else if (c[i] < '\177’) {
c[i] = (char) (c[i] + 65248);

}
}
String result = new String(c);
return result;
}

/**
* 全角を半角に変換
*
* @param strTarget
* String.
* @return 半角文字列
*/
public static String FullToHalf(String strTarget) {

char c[] = strTarget.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == '\u3000’) {
c[i] = ' ';
} else if (c[i] > '\uFF00’ && c[i] < '\uFF5F’) {
c[i] = (char) (c[i] – 65248);

}
}
String result = new String(c);

return result;
}

public static void main(String[] args) {
String cft = “tokyo city";

String cft1 = “TOKYO CITY";

String result = HalfToFull(cft);

String result1 = FullToHalf(cft1);

System.out.println(cft + “\n" + result);
System.out.println(“**********************");
System.out.println(cft1 + “\n" + result1);

}

}

結果
tokyo city
tokyo city
**********************
TOKYO CITY
TOKYO CITY

Java

Posted by arkgame