C#等价的python maketrans和translate

时间:2009-10-22 21:58:15

标签: c# python

我在哪里可以找到Python maketrans和翻译的C#等价的代码? 谢谢!

1 个答案:

答案 0 :(得分:2)

这应该会带你到处:

public class MakeTrans
{
    private readonly Dictionary<char, char> d;
    public MakeTrans(string intab, string outab)
    {
        d = Enumerable.Range(0, intab.Length).ToDictionary(i => intab[i], i => outab[i]);
        //d = new Dictionary<char, char>();
        //for (int i = 0; i < intab.Length; i++)
        //    d[intab[i]] = outab[i];
    }
    public string Translate(string src)
    {
        System.Text.StringBuilder sb = new StringBuilder(src.Length);
        foreach (char src_c in src)
            sb.Append(d.ContainsKey(src_c) ? d[src_c] : src_c);
        return sb.ToString();
    }
}

您有责任确保进出口的长度相同。您可以添加删除字母等功能。

字典构造以一种很酷的LINQ-y方式完成。它有点不明显,因此提供了注释掉的代码并执行相同的操作。

以下是它在python(example lifted from here)中的外观:

>>> from string import maketrans   # Required to call maketrans function.
>>>
>>> intab = "aeiou"
>>> outtab = "12345"
>>> trantab = maketrans(intab, outtab)
>>>
>>> str = "this is string example....wow!!!";
>>> print str.translate(trantab);
th3s 3s str3ng 2x1mpl2....w4w!!!

这是C#测试代码:

    static void Main(string[] args)
    {
        MakeTrans.MakeTrans mt = new MakeTrans.MakeTrans("aeiou", "12345");
        Console.WriteLine("{0}", mt.Translate("this is string example....wow!!!"));
    }

这是输出:

th3s 3s str3ng 2x1mpl2....w4w!!!