[Mono-list] System.Text.RegularExpression question

Grundgeiger, Dave dave.grundgeiger@esker.com
Fri, 16 Apr 2004 09:41:53 -0500


Hi Rob.

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.)

-- Dave

----------------------------------------
// Test class.
class MainClass
{
	public static void Main(string[] args)
	{
		StringTranslator t = 
			new StringTranslator("uzmdclatbg@yxrjeskiohvf$wnqp",

			                     "abcdefghijklmnopqrstuvwxyz
,");
		string text = t.Translate("tcyyjpqfjkyd");
		System.Console.WriteLine(text);
	}
}

// Translator class.
class StringTranslator
{
	// 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
same length.");
		
		ht = new System.Collections.Hashtable();
		
		for (int i=0; i<from.Length; ++i)
			ht.Add(from[i], to[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;
			else
				retval += s[i];
		}
		return retval;
	}
}
----------------------------------------

-----Original Message-----
From: Rob Hudson [mailto:rob@euglug.net] 
Sent: Thursday, April 15, 2004 5:53 PM
To: Mono-list
Subject: [Mono-list] System.Text.RegularExpression question

Hello,

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[1].  I converted the same program
in Python when I was learning some Python[2].

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.

Cheers!
Rob

[1] http://www.cogit8.org/rob/code/txt/cryptogram.txt
[2] http://www.cogit8.org/rob/blog/Languages/Python/200307180749.txt