13

このアルゴリズムは、「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]
}
4

2 に答える 2

21

したがって、すべてのインデックスを 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から始めて、常にギャップを残したいですか?

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:

更新「これ以外の代替コーディングはありますか?」

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

デモ

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
于 2013-01-19T10:47:27.473 に答える
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];
}
于 2013-01-19T10:50:37.110 に答える