1
2

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 3 years have passed since last update.

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

Last updated at Posted at 2021-04-26

ソースコード

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で変換しています。

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?