AllTheTimeWorld.com

csharp stringsAnagrams

Anagrams

Details for creating the form

Anagrams

Details for creating the form

Anagrams

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

:

  1. There is a labellabel lblInstructions with the words "Enter your social security number as 9 digits:"
  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:
// Programmer: Janet Joy
// User enters a word and the letters are scrambled to create an anagram.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace String1
{
    public partial class Form1 : Form
    {
        // Declare and initialize the random number seed just once.
        Random random = new Random();
        public Form1()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            String s = txtInput.Text;
            lblOutput.Text = scramble(s);
        }
        private String scramble(String s)
        {
            char[] ch = s.ToCharArray();
            // The first loop scrambles the letters.
            int i;
            // For each letter in word swap it with another letter chosen randomly.
            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;
            }
            // The second loop puts them back together as a string.
            String output = "";
            for (i = 0; i < s.Length; i++) output += ch[i];
            return output;
        }

    }
}
Experiment: Use a loop to create 10 anagrams and add them to a list box.