1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Java]特定の半角文字を全角文字に変換

Last updated at Posted at 2021-04-26

半角記号を全角記号に変換してくれという依頼を受けることがあるため、メモとして残します。

方法① 半角文字と全角文字の文字コードの差分を加算する

英数字と一部の記号は全角と半角でコードの並び順が一致しているため、全角と半角の差分の65248を加算することで全角にすることができる。

sample.java
public class Sample {
    // 全角にする文字
	private static final Character[] SYMBOLS = {
			'a', 'b', 'c', '1', '2', '3', '&', '_', '-'
	};

	public static void main(String[] args) {
		String halfWidth = "a1_";
		String fullWidth = "a1_";
        // 文字コードの差分が65248になるか確認
		for (int i = 0;i < halfWidth.length();i++) {
			System.out.println(fullWidth.charAt(i) - halfWidth.charAt(i));
            // 65248
		};

		String target = "abc&123_def-456";
		System.out.println(toFullWidth(target));
        // abc&123_def-456
	}

	private static String toFullWidth(String target) {
		char[] charArray = target.toCharArray();
		StringBuilder sb = new StringBuilder();
		for (char c : charArray) {
			if (Arrays.asList(SYMBOLS).contains(c)) {
                // 半角の文字コードに65248を加算して全角に変換 
				sb.append((char)(c + 65248));
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}

}

方法② 全角にする文字をMapで定義しておく

sample.java
public class Sample {

    // 全角にしたい文字
	private static final Map<String, String> SYMBOL_MAP;
	static {
		Map<String, String> map = new HashMap<>();
		map.put("a", "a");
		map.put("b", "b");
		map.put("c", "c");
		map.put("1", "1");
		map.put("2", "2");
		map.put("3", "3");
		map.put("&", "&");
		map.put("_", "_");
		map.put("-", "-");
		// 変更不可のマップを生成
		SYMBOL_MAP = Collections.unmodifiableMap(map);
	}

	public static void main(String[] args) {
		String target = "abc&123_def-456";
		System.out.println(toFullWidth(target));
        // abc&123_def-456
	}

	private static String toFullWidth(String target) {
		String[] strArray = target.split("");
		StringBuilder sb = new StringBuilder();
		for (String s : strArray) {
			if (SYMBOL_MAP.containsKey(s)) {
                // Mapから全角文字を取得 
				sb.append(SYMBOL_MAP.get(s));
			} else {
				sb.append(s);
			}
		}
		return sb.toString();
	}

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?