C#循环增加2个麻烦 [英] C# for loop increment by 2 trouble
问题描述
此算法将通过将 A, B存储到索引8和索引9中来存储从数组A到数组B的字符串
我真正开始使B的数组大小为10,因为稍后我会在这里放一些其他东西。
This algorithm is about to store strings from Array A to Array B by storing "A", "B" to Index 8 and Index 9 I really initiate to make the array size of B to be 10 because later I will put some other things there.
我的部分代码:
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:
So you want to increment every index with 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];
}
Index: 0 Value:
Index: 1 Value:
Index: 2 Value: A
Index: 3 Value: B
Index: 4 Value: C
Index: 5 Value: D
编辑:因此,您想从B中的索引0开始并始终留有间隔吗?
Edit: So you want to start with index 0 in B and always leave a gap?
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];
}
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:
更新除此以外,还有其他替代编码吗?
Update " Is there any alternative coding aside from this?"
您可以使用Linq,尽管它的可读性较差比简单的循环更有效:
You can use Linq, although it would be less readable and efficient than a simple loop:
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 ):
Final Update according to your last comment(start with index 1 in B):
for (int i = 1; (i-1) / 2 < A.Length; i += 2)
{
B[i] = A[(i-1) / 2];
}
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
这篇关于C#循环增加2个麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!