今回はunityを使っています。
また、本記事は『Microsoft.VisualBasic』を使わない方法で解説していきます。
Microsoft.VisualBasicを使ったほうがスマートにかけますが、環境依存したくないという方はこちらでいいかなと思います。
そして、今回は「入力フォームにカタカナを入れてボタン押下時にコンソールに入力文字列を表示する」という内容でやっていきます。
カタカナをひらがなに変換する
今回のコードの処理内容は主に3つです。
【11~20行目】
ボタン押下時にひらがなに変換した文字列をコンソールに表示する。
【26~37行目】
複数のカタカナを1文字ずつひらがなに変換し、その変換後の値を返す。
【42~93行目】
カタカナをキーにして、対応するひらがなを返すDictionaryを作成する。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
private Dictionary<string, string> _hiraganaConverter = new Dictionary<string, string>(); void Start() { CreateHiraganaConverter(); } /// <Summary> /// ボタン押下時に呼び出される処理 /// </Summary> public void OnButton() { GameObject objCanvas = GameObject.Find("Canvas"); GameObject objInputField = objCanvas.transform.Find("InputField").gameObject; GameObject objInputFieldText = objInputField.transform.Find("Text").gameObject; Text inputFieldText = objInputFieldText.GetComponent<Text>(); Debug.Log(ConvertHiragana(inputFieldText.text)); } /// <Summary> /// 複数のカタガナをひらがなに変換して返す /// </Summary> private string ConvertHiragana(string textValue) { string afterTextValue = ""; for (int i = 0; i < textValue.Length; i++) { string s = _hiraganaConverter[textValue[i].ToString()]; afterTextValue += s; } return afterTextValue; } /// <Summary> /// カタカナをキーにひらがなを返すDictionaryを作成 /// </Summary> private void CreateHiraganaConverter() { var hiraganaArray = new string[15, 5] { { "あ","い","う","え","お" }, { "か","き","く","け","こ" }, { "さ","し","す","せ","そ" }, { "た","ち","つ","て","と" }, { "な","に","ぬ","ね","の" }, { "は","ひ","ふ","へ","ほ" }, { "ま","み","む","め","も" }, { "や","っ","ゆ","空白2","よ" }, { "ら","り","る","れ","ろ" }, { "わ","空白3","を","空白4","ん" }, { "が","ぎ","ぐ","げ","ご" }, { "ざ","じ","ず","ぜ","ぞ" }, { "だ","ぢ","づ","で","ど" }, { "ば","び","ぶ","べ","ぼ" }, { "ぱ","ぴ","ぷ","ぺ","ぽ" } }; var katakanaArray = new string[15, 5] { { "ア","イ","ウ","エ","オ" }, { "カ","キ","ク","ケ","コ" }, { "サ","シ","ス","セ","ソ" }, { "タ","チ","ツ","テ","ト" }, { "ナ","ニ","ヌ","ネ","ノ" }, { "ハ","ヒ","フ","ヘ","ホ" }, { "マ","ミ","ム","メ","モ" }, { "ヤ","ッ","ユ","空白2","ヨ" }, { "ラ","リ","ル","レ","ロ" }, { "ワ","空白3","ヲ","空白4","ン" }, { "ガ","ギ","グ","ゲ","ゴ" }, { "ザ","ジ","ズ","ゼ","ゾ" }, { "ダ","ヂ","ヅ","デ","ド" }, { "バ","ビ","ブ","ベ","ボ" }, { "パ","ピ","プ","ペ","ポ" } }; int katakanaLineCount = katakanaArray.GetLength(0); for (int i = 0; i < katakanaLineCount; i++) { int targetLineCount = katakanaArray.GetLength(1); for (int j = 0; j < targetLineCount; j++) { _hiraganaConverter.Add(katakanaArray[i, j] , hiraganaArray[i, j]); } } } |
入力フォームに「アイウエオ」と入力し、OKボタンを押すと、コンソールに「あいうえお」と表示されるようになります。
スポンサーリンク