Combining two lines in a text box

I just found out about the basics of cryptography, and I wanted to give one of the methods called zigzag transport .
 This whole method combines the whole sentence and gives them an index starting at zero.
it then splits the even indexed characters into an array and the odd ones into another array.
When I convert two arrays to strings and then put them in a text box, only the first row appears.

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;
}
+4
source share
3 answers

Actually, your code is more complicated. The same can be done with simple strings; there is no need to convert to arrays in char:

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;

, (, 10, 20 ), 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();
+2

char. <br/>

char[] even = new char[whole.Length/2]; 
char[] odd = new char[whole.Length/2];
+4

Using a class is a StringBuildermore elegant approach instead of creating 2 instances String.

Implementation: DotnetFiddler

+1
source

Source: https://habr.com/ru/post/1689358/


All Articles