C#for循环增加2个麻烦

时间:2013-01-19 10:33:07

标签: c#-4.0

该算法即将存储" A"," B"" B"指数8和指数9 我真的开始将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 个答案:

答案 0 :(得分:16)

所以你想用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

答案 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];
}