ruby字串的encoding,force_encoding,encode,encode!轉碼(編碼轉換)
阿新 • • 發佈:2021-12-23
ruby1.9開始對字串編碼支援已經比較完善,我們可以直接通過使用String類的例項方法encoding,force_encoding,encode,encode!進行相關的編碼操作。
學習記錄用。轉載自網路,詳細看參考連結
encoding
ruby1.9中為每個字串物件增加了encoding資訊
1.9.3p392 :001 > '我還是不懂'.encoding => #<Encoding:UTF-8> 1.9.3p392 :002 >
force_encoding
某些情況下這個附加編碼資訊可能不正確我們可以修正它
1.9.3p392 :011 > x='我還是不懂' => "我還是不懂" 1.9.3p392 :012 > x.encoding => #<Encoding:UTF-8> 1.9.3p392 :013 > x.bytes.to_a => [230, 136, 145, 232, 191, 152, 230, 152, 175, 228, 184, 141, 230, 135, 130] 1.9.3p392 :014 > x.force_encoding 'gbk' => "\x{E688}\x{91E8}\x{BF98}\x{E698}\x{AFE4}\x{B88D}\x{E687}\x82" 1.9.3p392 :015 > x.encoding => #<Encoding:GBK> 1.9.3p392 :016 > x.bytes.to_a => [230, 136, 145, 232, 191, 152, 230, 152, 175, 228, 184, 141, 230, 135, 130] 1.9.3p392 :017 >
注意:force_encoding方法只是改變了字串物件的編碼資訊,並沒有改變字串物件實際儲存的內容。
encode、encode!
在ruby1.9之前如我我們需要編碼轉換則需要使用一些外部庫, 現在我們可以直接使用String物件的例項方法encode,encode!進行操作
encode(encoding [, options] ) → str click to toggle source encode(dst_encoding, src_encoding [, options] ) → str encode([options]) → str encode!(encoding [, options] ) → str click to toggle source encode!(dst_encoding, src_encoding [, options] ) → str
詳細的api請參考這裡
1.9.3p392 :009 > x='我還是不懂' => "我還是不懂" 1.9.3p392 :010 > x.encoding => #<Encoding:UTF-8> 1.9.3p392 :011 > x.bytes.to_a => [230, 136, 145, 232, 191, 152, 230, 152, 175, 228, 184, 141, 230, 135, 130] 1.9.3p392 :012 > y=x.encode 'gbk','utf-8' => "\x{CED2}\x{BBB9}\x{CAC7}\x{B2BB}\x{B6AE}" 1.9.3p392 :013 > y.encoding => #<Encoding:GBK> 1.9.3p392 :014 > y.bytes.to_a => [206, 210, 187, 185, 202, 199, 178, 187, 182, 174] 1.9.3p392 :015 > x.encode! 'gbk','utf-8' => "\x{CED2}\x{BBB9}\x{CAC7}\x{B2BB}\x{B6AE}" 1.9.3p392 :016 > x.encoding => #<Encoding:GBK> 1.9.3p392 :017 > x.bytes.to_a => [206, 210, 187, 185, 202, 199, 178, 187, 182, 174] 1.9.3p392 :018 >
可以看到encode改變了編碼資訊同時也改變了字串物件儲存的內容
參考 :http://blog.bccn.net/%E9%9D%99%E5%A4%9C%E6%80%9D/15131
總結
- encdoing用來檢視字串的編碼資訊。
- force_encoding用來修正字串編碼資訊,注意是修正。
- encode,encode!用來轉碼字串。