使用者輸入時常混入全形數字(Fullwidth),但資料庫、驗證邏輯、計算通常要求半形數字。本文提供一個高效的靜態方法,將字串中的全形數字(Unicode 碼位 U+FF10 ~ U+FF19)轉換為半形數字(U+0030 ~ U+0039)。
///
/// 將字串中的全形數字轉換為半形數字
///
/// 含全形數字的字串
/// 轉換後的字串
public static string FullWidthDigitsToHalfWidth(string input)
{
if (string.IsNullOrEmpty(input)) return input;
char[] chars = input.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
// 全形數字範圍:U+FF10 (0) ~ U+FF19 (9)
if (c >= '\uFF10' && c <= '\uFF19')
{
// 差值固定為 0xFEE0
chars[i] = (char)(c - 0xFEE0);
}
}
return new string(chars);
}
U+FF01 ~ U+FF5E,與半形對應字元相差 0xFEE0 (65248)。U+FF10 (0) ~ U+FF19 (9)。0xFEE0 即可得到對應半形字元,無需逐位元操作,效能更佳。public static class StringExtensions
{
/// 全形轉半形 (含標點、英文字母、數字、空白)
public static string ToHalfWidth(this string input)
{
if (string.IsNullOrEmpty(input)) return input;
char[] chars = input.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
if (c == '\u3000') { chars[i] = ' '; continue; } // 全形空白
if (c >= '\uFF01' && c <= '\uFF5E') chars[i] = (char)(c - 0xFEE0);
}
return new string(chars);
}
/// 半形轉全形
public static string ToFullWidth(this string input)
{
if (string.IsNullOrEmpty(input)) return input;
char[] chars = input.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
char c = chars[i];
if (c == ' ') { chars[i] = '\u3000'; continue; }
if (c >= '\u0021' && c <= '\u007E') chars[i] = (char)(c + 0xFEE0);
}
return new string(chars);
}
}
[TestMethod]
public void FullWidthDigitsToHalfWidth_Test()
{
Assert.AreEqual("12345", StringExtensions.FullWidthDigitsToHalfWidth("12345"));
Assert.AreEqual("Price: 100", StringExtensions.FullWidthDigitsToHalfWidth("Price: 100"));
Assert.AreEqual("ABC", StringExtensions.FullWidthDigitsToHalfWidth("ABC")); // 非數字不變
Assert.AreEqual("", StringExtensions.FullWidthDigitsToHalfWidth(""));
Assert.AreEqual(null, StringExtensions.FullWidthDigitsToHalfWidth(null));
}