Hello Everybody!
I thought someone could help me with the following text conversion: a text has to be converted in accordance with a conversion table, which might look like that:
'a' -> 'b', 'c' -> 'd', etc. That is, one symbol is substituted with another according to the table.
My questions are: how can I build the conversion table (an array?, a structure?) and how can I further implement it into a conversion method?
Thank you,
Stig
Loading
AlanPosted Nov 6, 2008, 11:29 AM
If you mean that more than one letter could map to the same key, then that's no problem. In your example the key would start with "cc".
If one letter always mapped to a two letter combination, then again that's no great problem - the key would contain 52 letters i.e. the 26 two letter combinations in order and so it would be easy to pick each one out.
However, if a two letter combination could map to a single letter that would be much more awkward. My first thought is that you would need two string arrays: one for the 'alphabet' and one for the key which would have a 1 to 1 correspondence with each other.
The 'alphabet' would include entries not only for single letters, when not used in combination but for all possible combinations as well. Parsing would be awkward as in some cases you'd need to examine the next letter as well to see whether it formed a valid combination within your alphabet.
StigPosted Nov 6, 2008, 11:01 AM
I've just imagined a situation, when more than one alphabet symbol might need only one key, and probably vice versa, i.e. 'ab' -> 'c', 'd'->'ef'. How the alphabet and string keys are to be presented then?
Stig
AlanPosted Nov 6, 2008, 10:36 AM
For simple text conversion, the easiest approach is to use a string key which contains the characters for which the letters of the alphabet are to be substituted in the same order. You can then use this key as in the following example:
using System;
class Program
{
static void Main()
{
string alphabet = "abcdefghijklmnopqrstuvwxyz";
Console.WriteLine(alphabet);
string key = "bcdzyaefgvwxhijstuklmpqrno";
Console.WriteLine(key);
string text = "Too many cooks spoil the broth";
Console.WriteLine(text);
string conversion = ConvertText(key,text);
Console.WriteLine(conversion);
Console.ReadLine();
}
static string ConvertText(string key, string text)
{
char[] chars = new char[text.Length];
char c;
for(int i = 0; i < text.Length; i++)
{
c = text[i];
if (c >= 'a' && c <= 'z')
{
chars[i] = key[(int)c - 97];
}
else if (c >= 'A' && c <= 'Z')
{
chars[i] = Char.ToUpper(key[(int)c - 65]);
}
else
{
chars[i] = text[i];
}
}
return new string(chars);
}
}