Sunday, October 17, 2010

C# Tutorial: Read/Write Characters from/to a String [Simple TextEncoder]

Here is the code

private void button3_Click(object sender, EventArgs e)
{
    StringReader str = new StringReader(textBox1.Text); // Read from textBox1.Text.
    StringWriter stw = new StringWriter();
    // This algorithm reverses the code (ASCII) of a char. Example: "a" is 97; the new code will be 79, wich is "O".
    int key, chr, newChr;
    do
    {
        key = str.Read(); // Read the int value (ASCII code) of the char
        chr = key; newChr = 0;
        // Reverse the code of the char
        while (key != -1 && chr != 0)
        {
            newChr = newChr * 10 + chr % 10;
            chr /= 10;
        }
        // Add the new char to the StringWriter
        if (key != -1) stw.Write((char)newChr);
        // Repeat this while there are chars in the string. -1 means the end of a string.
    } while (key != -1);
    // Converts stw to string and adds it to textBox1.Text.
    textBox1.Text = stw.ToString(); 
}

Or download the solution

No comments:

Post a Comment