ソースコード
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 |
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で変換しています。