LoginSignup
1
0

More than 3 years have passed since last update.

[Ruby] SJIS (CP932) のはずなのにエンコーディングが UTF-8 の文字列を UTF-8 に変換する

Last updated at Posted at 2019-09-12

やりたいこと

本当は SJIS (CP932) のはずなのにエンコーディングが UTF-8 と解釈されている文字列を、SJIS と判断した上で UTF-8 に変換したい。

str = '米津玄師'.encode(Encoding::SJIS).force_encoding(Encoding::UTF_8)
#=> "\x95ĒÌ\xBA\x8Et"
str.encoding
#=> #<Encoding:UTF-8>
str.encode(Encoding::UTF_8)
#=> "\x95ĒÌ\xBA\x8Et"
# ???
#=> "米津玄師"

方法

NKF.guessString#encode (第 2 引数に変換元のエンコーディングを指定する) を使う。

require 'nkf'

str = '米津玄師'.encode(Encoding::SJIS).force_encoding(Encoding::UTF_8)
str.encode(Encoding::UTF_8, NKF.guess(str)) # NKF.guess(str) #=> #<Encoding:Shift_JIS>
#=> "米津玄師"

str = '米津玄師'
str.encode(Encoding::UTF_8, NKF.guess(str))
#=> "米津玄師"
1
0
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
0