LoginSignup
0
1

More than 5 years have passed since last update.

Unicode文字列のサロゲートペア文字の文字コードを取得する

Last updated at Posted at 2017-06-29

Scalaで絵文字などのサロゲートペアを含むUnicode文字列を変換し、サロゲートペア文字の文字コードを取得する方法。
地味にはまった。 単純にtoHexStringして連結すればOK

  def convert(str: String): String = {
    val sb = new StringBuilder
    for (i <- 0 until str.length)
      yield sb.append("\\u%s".format(str(i).toHexString))
    sb.toString
  }

なお、
http://qiita.com/sifue/items/039846cf8415efdc5c92
に記載の通り、Java的に書く方法も存在するが、
Character.codePointAt(str, 0) の値が4桁x2のサロゲートペア文字列ではなく、5桁の値が取得されてしまった。
Scalaであれば、str(i).toInt.toHexStringでやりたいことは出来るので、難しく考えなくても良いかもしれない。

0
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
0
1