.NET - Translation between Simplified and Traditional Chinese

  • 调用Visual Basic的繁简转换功能
static void TestVB()
{
    var zh_TW = Microsoft.VisualBasic.Strings.StrConv("数据库", Microsoft.VisualBasic.VbStrConv.TraditionalChinese, 0);
    Console.WriteLine(zh_TW);
    var zh_CN = Microsoft.VisualBasic.Strings.StrConv("數據庫", Microsoft.VisualBasic.VbStrConv.SimplifiedChinese, 0);
    Console.WriteLine(zh_CN);
}

输出结果

數據庫
数据库
  • 通过字符映射表进行繁简转换
using System;
using System.Collections.Generic;
using System.Linq;

namespace cntw
{
    public class TsConv
    {
        private Dictionary<char, char> _stCharMap = new Dictionary<char, char>();
        private Dictionary<char, char> _tsCharMap = new Dictionary<char, char>();

        public TsConv(string path)
        {
            var content = System.IO.File.ReadAllText(path);
            var items = content.Split(new char[] { ' ', ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in items) {
                var st = item.Split('=');
                if (st.Length == 2) {
                    _stCharMap[st[0][0]] = st[1][0];
                    _tsCharMap[st[1][0]] = st[0][0];
                }
            }
        }

        public char ToSimplified(char c)
        {
            return _tsCharMap.ContainsKey(c) ? _tsCharMap[c] : c;
        }

        public char ToTraditional(char c)
        {
            return _stCharMap.ContainsKey(c) ? _stCharMap[c] : c;
        }

        public string ToSimplified(string s)
        {
            return new string(s.Select(c => ToSimplified(c)).ToArray());
        }

        public string ToTraditional(string s)
        {
            return new string(s.Select(c => ToTraditional(c)).ToArray());
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var tsconv = new TsConv(@"e:\temp\chmap.txt");
            var t = @"數據庫内容匹配繁體";
            var s = tsconv.ToSimplified(t);
            Console.WriteLine($"source: {t}");
            Console.WriteLine($"target: {s}");
        }
    }
}

运行结果

source: 數據庫内容匹配繁體
target: 数据库内容匹配繁体

下载繁简字符对照表