25
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Stringクラスにひらがな・カタカナ変換をextensionする

Posted at

ひらがな・カタカナについて

  • "ひらがな"とは、0x3041の"ぁ"から0x3096の"ゖ"とする
  • "カタカナ"とは、0x30A1の"ァ"から0x30F6の"ヶ"とする
  • 半角カタカナは無視

コード

extension String {
    func katakana() -> String {
        var str = ""

        // 文字列を表現するUInt32
        for c in unicodeScalars {
            if c.value >= 0x3041 && c.value <= 0x3096 {
                str.append(UnicodeScalar(c.value+96))
            } else {
                str.append(c)
            }
        }

        return str
    }

    func hiragana() -> String {
        var str = ""
        for c in unicodeScalars {
            if c.value >= 0x30A1 && c.value <= 0x30F6 {
                str.append(UnicodeScalar(c.value-96))
            } else {
                str.append(c)
            }
        }

        return str
    }
}

var hoge = "ほげピヨ"
hoge.katakana()     //"ホゲピヨ"
hoge.hiragana()     //"ほげぴよ"
25
20
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
25
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?