11
6

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.

Elixir: ひらがなとカタカナの相互変換

Posted at

Elixirでひらがなをカタカナに、あるいはカタカナをひらがなに変換したい場合、Exkanjiというパッケージが使えます。

しかし、Exkanjiは外部コマンド nkf を利用しているので、環境構築にひと手間かかるし、パフォーマンス的にも不利です。

Unicodeでは、対応するひらがなとカタカナのコードポイントはちょうど 0x60 離れているので、外部コマンドを使ったり、変換表を作ったりしなくても単純な計算で求められます。

実装

次に、私が作った StringHelper モジュールのソースコードを示します。

defmodule StringHelper do
  @moduledoc """
  文字列を扱う汎用的なヘルパー関数群。
  """

  @doc """
  与えられた文字列に含まれるひらがなをカタカナに変換して返す。
  """
  def hiragana2katakana(source) do
    source
    |> String.codepoints()
    |> Enum.map(&do_convert_h2k(&1))
    |> Enum.join()
  end

  defp do_convert_h2k(cp) when cp < "\u3041" or cp > "\u3096", do: cp

  defp do_convert_h2k(cp) do
    <<n::utf8>> = cp
    m = n + 0x60
    <<m::utf8>>
  end

  @doc """
  与えられた文字列に含まれるカタカナをひらがなに変換して返す。
  """
  def katakana2hiragana(source) do
    source
    |> String.codepoints()
    |> Enum.map(&do_convert_k2h(&1))
    |> Enum.join()
  end

  defp do_convert_k2h(cp) when cp < "\u30A1" or cp > "\u30F6", do: cp

  defp do_convert_k2h(cp) do
    <<n::utf8>> = cp
    m = n - 0x60
    <<m::utf8>>
  end
end

関数 String.codepoints/1 は、文字列をコードポイント(Unicodeキャラクター)のリストに変換します。

パターンマッチング <<n::utf8>> = cp で、コードポイント cp に与えられた整数値が n にセットされます。

ひらがなからカタカナに変換する場合は、n0x60 を加えて m とし、<<m::utf8>> でコードポイントに戻しています。逆に、カタカナからひらがなに変換する場合は、n から 0x60 を引いています。

なお、このモジュールはいわゆる「半角カナ」には対応していません。

利用法

上記のソースコードを string_helper.ex という名前で適当なディレクトリに保存し、コンパイルしてください。

$ elixirc string_helper.ex

IEx を起動して、こんな風に使います。

$ iex
iex(1)> StringHelper.hiragana2katakana("かっとやさい")
"カットヤサイ"
iex(2)> StringHelper.katakana2hiragana("ダブルクォート")
"だぶるくぉーと"
11
6
1

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
11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?