【问题标题】:C# for loop increment by 2 troubleC# for 循环递增 2 麻烦
【发布时间】:2016-07-28 00:18:22
【问题描述】:

此算法即将通过将“A”、“B”存储到索引 8 和索引 9 来将字符串从数组 A 存储到数组 B 我真的开始将B的数组大小设置为10,因为稍后我会放一些其他的东西。

我的部分代码:

string[] A = new string[]{"A","B"}
string[] B = new string[10]; 
int count;

for(count = 0; count < A.length; count++)
{
      B[count] = A[count]
}

【问题讨论】:

  • 想象一下如何将某个值增加 2?你知道count++是什么意思吗?
  • * 在 C# 中进行乘法运算。
  • count += 2 C# 中 for 循环的更新端需要使用复合赋值。

标签: c#-4.0


【解决方案1】:

所以你想用 2 递增每个索引:

string[] A = new string[] { "A", "B", "C", "D" };
string[] B = new string[A.Length + 2];
for (int i = 0; i < A.Length; i++)
{
    B[i + 2] = A[i];
}

Demo

Index: 0 Value: 
Index: 1 Value: 
Index: 2 Value: A
Index: 3 Value: B
Index: 4 Value: C
Index: 5 Value: D

编辑:所以你想从 B 中的索引 0 开始,并且总是留有空隙?

string[] A = new string[] { "A", "B", "C", "D" };
string[] B = new string[A.Length * 2 + 2]; // you wanted to add something other as well
for (int i = 0; i/2 < A.Length; i+=2)
{
    B[i] = A[i / 2];
}

Demo

Index: 0 Value: A
Index: 1 Value: 
Index: 2 Value: B
Index: 3 Value: 
Index: 4 Value: C
Index: 5 Value: 
Index: 6 Value: D
Index: 7 Value: 
Index: 8 Value: 
Index: 9 Value:

更新 "除此之外还有其他编码方式吗?"

您可以使用 Linq,尽管它的可读性和效率不如简单循环:

String[] Bs = Enumerable.Range(0, A.Length * 2 + 2) // since you want two empty places at the end
 .Select((s, i) => i % 2 == 0 && i / 2 < A.Length ? A[i / 2] : null)
 .ToArray();

根据您上一条评论的最终更新从 B 中的索引 1 开始):

for (int i = 1; (i-1) / 2 < A.Length; i += 2)
{
    B[i] = A[(i-1) / 2];
}

Demo

Index: 0 Value: 
Index: 1 Value: A
Index: 2 Value: 
Index: 3 Value: B
Index: 4 Value: 
Index: 5 Value: C
Index: 6 Value: 
Index: 7 Value: D
Index: 8 Value: 
Index: 9 Value

【讨论】:

  • @ChrisAplaon:我已经编辑了我的答案。您也应该在问题中包含所需的输出。
  • 是的,先生,除此之外还有其他编码方式吗?对于像我这样的初学者来说理解。
  • @ChrisAplaon:为了完整起见,添加了(不合适的)Linq 方法。
  • 哇,我在网站的其他问题中看到了这种编码,但我仍然很难理解。顺便说一句,先生,非常感谢您。即使我手动跟踪代码,代码也能正常工作。
  • 先生,我想补充一个问题。可以吗?
【解决方案2】:

又一次尝试猜测你想要什么:

string[] A = new string[] { "A", "B", "C", "D" };
string[] B = new string[A.Length * 2];
for (int i = 0; i < A.Length; i++)
{
    B[i*2] = A[i];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2013-03-26
    • 1970-01-01
    相关资源
    最近更新 更多