Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

swift UTF8からSJISに変換するときに、数値文字参照も使用する

問題 文字コード変換だけでは望ましい結果にならない


String.data(using: .shiftJIS)だと失敗します。

String.data(using: .shiftJIS, allowLossyConversion: true)


  1. 1文字ごとにShiftJIS(EUC-JP)に変換できるか確認する
  2. 変換できない場合にはhtmlの文字参照に起きかえる
  3. ShiftJIS(EUC-JP)変換を行なう というステップを取ります。
var postStr: String = "(´・ω・`)"
let postStrChaRef: String = postStr.characterReferenceSJIS() // 文字参照変換
let postData:Data? = postStrChaRef.data(using: .shiftJIS)  // SJIS変換

import Foundation
extension String {
    func characterReferenceSJIS() -> String {
        var buf = ""
        for c in self.map({ String($0) }) {
            if c.canBeConverted(to: String.Encoding.shiftJIS) {
            } else {
                let buf1 = NSMutableString(string: c)
                CFStringTransform(buf1, nil, kCFStringTransformToXMLHex, false)
                buf.append(buf1 as String)
        return buf
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
Sign upLogin
Help us understand the problem. What are the problem?