58
58

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 5 years have passed since last update.

JavaのUnicode文字列の変換用メソッド("あ" <-> "\u3042")

Posted at

コンソールからnative2asciiを実施しても良いのですが、Javaのコードの中で実施しなきゃいけない時に、よく書く短いコードなのでまとめておきます。

/**
 * Unicode文字列に変換する("あ" -> "\u3042")
 * @param original
 * @return
 */
private static String convertToUnicode(String original)
{
	StringBuilder sb = new StringBuilder();
	for (int i = 0; i < original.length(); i++) {
		sb.append(String.format("\\u%04X", Character.codePointAt(original, i)));
	}
	String unicode = sb.toString();
	return unicode;
}

/**
 * Unicode文字列から元の文字列に変換する ("\u3042" -> "あ")
 * @param unicode
 * @return
 */
private static String convertToOiginal(String unicode)
{
	String[] codeStrs = unicode.split("\\\\u");
	int[] codePoints = new int[codeStrs.length - 1]; // 最初が空文字なのでそれを抜かす
	for (int i = 0; i < codePoints.length; i++) {
		codePoints[i] = Integer.parseInt(codeStrs[i + 1], 16);
	}
	String encodedText = new String(codePoints, 0, codePoints.length);
	return encodedText;
}
58
58
3

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
58
58

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?