【C#】文字列の全角文字を半角文字に変換

ソースコード

FullWidthToHalfWidthConverter.cs
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class FullWidthToHalfWidthConverter
{
    private Encoding encoding = Encoding.GetEncoding("Shift_JIS");

    private Dictionary<char, char> FullWidthToHalfWidthDictionary = new Dictionary<char, char>
    {
        { 'ー','-'},
        { '「','['},
        { '」',']'},
        { '、',','},
        { '。','.'},
        { '・','/'},
    };

    private const int FullWidthHalfWidthDifference = 65248;
    private const int StartFullWidthCharSetByte = 65281;
    private const int EndFullWidthCharSetByte = 65374;

    public string Convert(string text)
    {
        string output = "";
        foreach (int c in text)
        {

            if (StartFullWidthCharSetByte <= c && c <= EndFullWidthCharSetByte) { output += (char)(c - FullWidthHalfWidthDifference ); continue; } if (FullWidthToHalfWidthDictionary.Keys.Any(k => (int)k == c))
            {
                output += FullWidthToHalfWidthDictionary[(char)c];
                continue;
            }

            output += (char)c;
        }

        return output;
    }

    public bool IsHalfWidth(string text)
    {
        return text.Length == encoding.GetByteCount(text);
    }
}

説明

半角英数字は文字コードの差を使用して変換、キーボードの日本語記号はDictionaryで変換しています。

この記事を書いた人

azure-recipe-user