C# equivalence of python maketrans and translate
Where co开发者_StackOverflowuld I find code of a C# equivalence of Python maketrans and translate? Thanks!
This should take you most of the way there:
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();
}
}
You're responsible for making sure that intab and outtab are the same length. You can add functionality for dropping letters, etc.
The dictionary construction is done in a cool LINQ-y way. It's a bit non-obvious, so the commented out code is provided and does the same thing.
Here's how it looks in 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!!!
Here is 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 is the output:
th3s 3s str3ng 2x1mpl2....w4w!!!
精彩评论