Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

コンソールから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;
}
sifue
N高等学校でプログラミングを教えているプログラマーで、学園のIT担当。「高校生からはじめる プログラミング」著者 ( https://www.amazon.co.jp/dp/4046019557/ ) 。 言語: Scala/JavaScript/Java ゲーム: LoL/フォトナ/クラロワ
https://www.soichiro.org/
dwango
Born in the net, Connected by the net.
https://dwango.co.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした