C # python maketrans equivalence and translation

Where can I find C # Python maketrans equivalence code and translate? Thank!

+2


source to share


1 answer


This will take you most of the way:

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();
    }
}

      

It is your responsibility to ensure that the intab and outtab are the same length. You can add functionality to remove letters, etc.

The dictionary construction is done in the cool LINQ-y style. This is a bit obscure, so commented code is provided and does the same.

This is how it looks in python ( example filmed 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!!!

      

Here is the C # test code:

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

      

And here's the output:

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

      

+2


source







All Articles