Try   HackMD

使用 C# 繁體轉簡體

tags: C#

前言

早期在寫單機的時候發現有這樣的功能,這邊把之前舊的使用方式和現在Core上使用的方式記錄一下。

說明

不會很難直接看實作吧

目錄

實作

舊方法(kernel32.dll)

網路上還可以找到幾種轉換方式,這邊的話是使用OS內建元件kernel32.dll的方式直接進行,代碼如下:

{ private const int LocaleSystemDefault = 0x0800; private const int LcmapSimplifiedChinese = 0x02000000; private const int LcmapTraditionalChinese = 0x04000000; [DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)] private static extern int LCMapString(int locale, int dwMapFlags, string lpSrcStr, int cchSrc, string lpDestStr, int cchDest); /// <summary> /// 繁體轉簡體 /// </summary> public static string ToSimplified(string argSource) { var t = new String(' ', argSource.Length); LCMapString(LocaleSystemDefault, LcmapSimplifiedChinese, argSource, argSource.Length, t, argSource.Length); return t; } /// <summary> /// 簡體轉繁體 /// </summary> public static string ToTraditional(string argSource) { var t = new String(' ', argSource.Length); LCMapString(LocaleSystemDefault, LcmapTraditionalChinese, argSource, argSource.Length, t, argSource.Length); return t; } }

執行結果如下:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

使用套件

在現在可以使用套件CHTCHSConv來進行,除了方便許多相容性也比較好。

套件下載完後使用方法如下,如果需要簡體轉繁體只需要調整ChineseConversionDirection參數即可

ChineseConverter.Convert("這是一段文字", ChineseConversionDirection.TraditionalToSimplified);

執行結果如下

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

結論

這邊單純紀錄一下功能使用上的差異,整體來說不會太難。



相關參考來源:
C# 繁簡轉換效能大車拚