[Mono-list] System.Text.RegularExpression question
Fri, 16 Apr 2004 09:41:53 -0500
I don't know of anything built into the framework that does that, but here's
a function for you. (Sorry about the MS namespaces, I code on the MS side
and am just a Mono lurker.)
// Test class.
public static void Main(string args)
StringTranslator t =
string text = t.Translate("tcyyjpqfjkyd");
// Translator class.
// Use a Hashtable for quick lookup of characters to be translated.
private System.Collections.Hashtable ht;
// Pass the from and to string to the constructor so that it can
// create an internal lookup table for speedy processing.
public StringTranslator(string from, string to)
if (from.Length != to.Length)
throw new System.ApplicationException(
"from and to must have the
ht = new System.Collections.Hashtable();
for (int i=0; i<from.Length; ++i)
// Translate a string. If you want to do in-place processing and
// possibly improve performance, you could rewrite this to take
// a StringBuilder object.
public string Translate(string s)
string retval = "";
for (int i=0; i<s.Length; ++i)
object val = ht[s[i]];
if (val != null)
retval += (char)val;
retval += s[i];
From: Rob Hudson [mailto:firstname.lastname@example.org]
Sent: Thursday, April 15, 2004 5:53 PM
Subject: [Mono-list] System.Text.RegularExpression question
Short and sweet: Does C# have a way to transpose letters?
I'm new to C# and as a learning tool, I'm trying to convert an old
cryptogram generator I wrote in perl. I converted the same program
in Python when I was learning some Python.
The Perl code had one line in it that I can't find in C#. The line is
similar to the following...
$text =~ tr/ABC/XYZ/;
...except it is the full alphabet tranposed to the full alphabet
randomly shuffled. It should replace each instance of 'A' with 'X',
each instance of 'B' with 'Y', etc.
The documentation at http://www.go-mono.com:8080/ says "To be added"
when looking up System.Text.RegularExpressions.Regex.
I realize I can run a loop and perform a Regex.Replace on each letter,
but thought there might be a better way.
Or maybe C# has a String.Translate method similar to Python?
Thanks for any help.