简体   繁体   中英

c# split string in 2. letter by letter

I need split my string in 2, one letter to each variable.

Example: string = "ABCDEFGHIJ" name1: ACEGI name2: BDFHJ

I done so far:

        var builderM = new StringBuilder();
        var builderK = new StringBuilder();

        for (int i = 0; i < s.Length; i++)
        {
            builderM.Append(s[i]);
            builderK.Append(s[i++]);
        }

        txtM.Text = builderM.ToString();
        txtK.Text = builderK.ToString();

But its showing same text in the 2.

you should use ++i instead of i++

    for (int i = 0; i < s.Length; i++)
    {
        builderM.Append(s[i]);
        if(i + 1 < s.Length) // to prevent IOR exception when count is odd.
             builderK.Append(s[++i]); // pre increment.
    }

the reason is that i++ is post incremented. that means i gets incremented after the expression therefor s[i++] will give you same item as s[i] .

Another approach would be to use LINQ to filter odd and even indices into two strings, something like:

var even = new string(input.Where((c, idx) => idx % 2 == 0).ToArray());
var odd = new string(input.Where((c, idx) => idx % 2 != 0).ToArray());

You can also use the modulus operator ( % ) to determine if the index is even or odd, and put the even indexes in the first array and the odd indexes in the second one:

for (int i = 0; i < s.Length; i++)
{
    if (i % 2 == 0) builderM.Append(s[i]);
    else builderK.Append(s[i]);
}

If you'd rather increment the i inside the for body, you have to repeat the check against s.Length (as we do in the for condition). Also, you will need to either move the post-increment to the previous line (so that i is incremented in time), or use a pre-increment:

// Move post-increment to previous line example:
for (int i = 0; i < s.Length; i++)
{
    builderM.Append(s[i++]);
    if (i < s.Length) builderK.Append(s[i]);
}

// Use a pre-increment example:
for (int i = 0; i < s.Length; i++)
{
    builderM.Append(s[i]);
    if (++i < s.Length) builderK.Append(s[i]);
}

If performance is not an issue, you can use LINQ:

    var name1 = String.Join(String.Empty, str.Where((v, i) => i % 2 == 0));
    var name2 = String.Join(String.Empty, str.Where((v, i) => i % 2 == 1));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM