Zebra0.com

csharp strings

Cryptograms

Start a new project named Cryptograms. Build the form as shown below

:

  1. There is a labellabel lblInstructions with the words "Enter a sentence to make a cryptogram:"
  2. There is a text boxtext box named txtInput.
  3. There is a buttonbutton, btnOK.
  4. There is a labellabel named lblOutput.
  5. Set the accept button for the form to btnOK.
  6. Write the code as shown below:
public partial class Form1 : Form
{
   Random random = new Random();
   ...

private void btnOK_Click(object sender, EventArgs e)
{
   String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   // Create the code by scrambling the alphabet.
   String code = scramble(alphabet);
   // Create codeCh as an array of characters to work with.
   char[] codeCh = code.ToCharArray();
   // Get the text from user.
   String s = txtInput.Text;
   // Cryptograms are always uppercase.
   s = s.ToUpper();
   // Create an array of the letters in the input.
   char[] message=s.ToCharArray();
   int i, pos;
   // For each letter in the messsage...
   for(i=0;i<s.Length;i++)
   {
      // Find the position of the char in the alphabet.
      pos = alphabet.IndexOf(message[i]);
      // If the char is a letter of the alphabet, replace with the code letter.
      // If not, it is a digit or other character, leave as is.
      if (pos >= 0) message[i] = codeCh[pos];
    }
    // Use the function to convert a char array to string.
    lblOutput.Text = charArrayToString(message);
}

private String charArrayToString(char[] ch)
{
   // Adds each letter in ch to s.
   String s = "";
   for (int i = 0; i < ch.Length; i++) s += ch[i];
   return s;
}

private String scramble(String s)
{
   // Scrambles the letters.
   char[] ch = s.ToCharArray();
   // The first loop scrambles the letters.
   int i;
   for (i = 0; i < s.Length; i++)
   {
      // r is a random position in array
      int r = random.Next(0, s.Length-1);
      // Swap char i and char r:
      char c = ch[i];
      ch[i] = ch[r];
      ch[r] = c;
   }
   // Use the function to convert a char array to string.
   return charArrayToString(ch);
 }
}

Notice that the punctuation is unchanged in the output.
Cryptograms always make sure that no letter of the alphabet is in the same position in the code.
This program doesn't do that. How would you implement that?

End of lesson, Next lesson: Files in C#