Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Convert between Romaji and Hiragana/Katakana

0.00/5 (No votes)
2 Jul 2014 1  
This is a dirtiest trick that shows you how to convert text between Romaji and Hiragana/Katakana

Introduction

Few years ago, when I developed a Japanese translation tool, I realized that user may not have a Japanese IME on their PC, so they cannot input a Japanese Text in my tool's textbox. Then, I wrote a method to convert between Romaji and Kana. The trick is about how I made my database (the order is the most important).

Using the Code

First, declare a List to store database:

private List<string> Database = new List<string>();

Convert Mode enum:

enum Mode
{
    Hiragana,
    Katakana,
    Romaji
}

Read data from text file:

private void GetDatabase()
{
    using (System.IO.StreamReader sr = new System.IO.StreamReader("Database.txt"))
    {
        while (!sr.EndOfStream)
        {
            string splitMe = sr.ReadLine();
            Database.Add(splitMe);
        }
    }
}

Convert method:

private string Convert(string text, Mode convertMode)
{
    text = text.ToLower();
    
    string roma = string.Empty;
    string hira = string.Empty;
    string kata = string.Empty;
    
    foreach (string row in Database)
    {
        var split = row.Split('@');
        roma = split[0];
        hira = split[1];
        kata = split[2];
        
        switch (convertMode)
        {
            case Mode.Romaji:
                text = text.Replace(hira, roma);
                text = text.Replace(kata, roma.ToUpper());
                break;
            case Mode.Hiragana:
                text = text.Replace(roma, hira);
                break;
            case Mode.Katakana:
                text = text.Replace(roma, kata);
                break;
        }
    }
    
    return text;
}

Points of Interest

This is a very simple code. Please download the source code and use this method when you have to deal with Japanese input. :)

EDIT: Thanks to Seishin#, I updated my code.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here