Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
56
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@sifue

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

コンソールから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;
}
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
56
Help us understand the problem. What are the problem?