简体   繁体   English

c#将字符串拆分为2。

[英]c# split string in 2. letter by letter

I need split my string in 2, one letter to each variable. 我需要将我的字符串分成2个,每个变量一个字母。

Example: string = "ABCDEFGHIJ" name1: ACEGI name2: BDFHJ 示例: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. 但是它在2中显示相同的文本。

you should use ++i instead of i++ 您应该使用++i而不是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. 原因是i++已过帐。 that means i gets incremented after the expression therefor s[i++] will give you same item as s[i] . 这意味着在表达式s[i++]给出与s[i]相同的项之后, i会递增。

Another approach would be to use LINQ to filter odd and even indices into two strings, something like: 另一种方法是使用LINQ将奇数和偶数索引过滤为两个字符串,例如:

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). 如果要在for主体中增加i ,则必须对s.Length重复检查(就像在for条件中所做的那样)。 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: 另外,您将需要将后增量移动到前一行(以便i随时间增加),或使用前增量:

// 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: 如果性能不是问题,则可以使用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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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