Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating two strings into a Textbox

I have been just learning about the basics of cryptography, and I wanted to give one of the methods called zigzag transposition a try.
All this method does is combining the entire sentence and give them index starting from zero.
it then separates the even indexed characters into an array and the odd ones into a different array .
When I convert the two arrays to strings and then place them in a textbox only the first string shows up.

private void ZigzagBu_Click(object sender, EventArgs e) {
    string s = PlaintextTB.Text;
    s = s.Replace(" ","");

    char[] whole = s.ToCharArray();
    char[] even = new char[whole.Length];
    char[] odd = new char[whole.Length];

    int evenIndex = 0;
    int oddIndex = 0;

    for(int i =0;i<whole.Length;i++) {
        if (i % 2 == 0) {
            even[evenIndex] = whole[i];
            evenIndex++;
        }
        else {
            odd[oddIndex] = whole[i];
            oddIndex++;
        }
    }

    s = new String(even);
    string m = new String(odd);

    CiphertextTB.Text = s+m;
}
like image 758
Skeptical Ant Avatar asked Mar 08 '23 14:03

Skeptical Ant


2 Answers

The problem was in the size of the char arrays. I solved it by <br/>

char[] even = new char[whole.Length/2]; 
char[] odd = new char[whole.Length/2];
like image 135
Skeptical Ant Avatar answered Mar 17 '23 17:03

Skeptical Ant


Actually, your code is over complicated. The same thing can be done with simple strings, no need to convert to char arrays:

var s = "0123456";
var even = "";
var odd = "";
for(int i=0; i<s.Length;i++)
{
    if(i % 2 == 0)
    {
        even  += s[i];
    }
    else
    {
        odd += s[i];
    }
}
var result = even + odd;

However, if your plain text string is even a bit long (say, 10, 20 chars) - a better implementation would be to use StringBuilder:

var s = "0123456";
var even = new StringBuilder();
var odd = StringBuilder();
for(int i=0; i<s.Length;i++)
{
    if(i % 2 == 0)
    {
        even.Append(s[i]);
    }
    else
    {
        oddAppend(s[i]);
    }
}
var result = even.Append(odd.ToString()).ToString();
like image 31
Zohar Peled Avatar answered Mar 17 '23 16:03

Zohar Peled