c#-4.0 - C# for 循环增加 2 麻烦

标签 c#-4.0

该算法即将通过将“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 增加每个索引:

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

关于c#-4.0 - C# for 循环增加 2 麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14413404/

相关文章:

c# - 在 C# 中使用 linq 更新 xml

c# - 从集合中移除对象

C#如何编写泛型方法

winforms - 如何在c# windows应用程序中上传多个文件

c#-4.0 - 如何在 Xamarin Forms 中更改 Windows Phone 上工具栏的背景颜色?

c# - 为什么参数没有更新?

c# - 在方法签名中使用 new 关键字通常只是为了提高可读性吗?

asp.net - 使用文本模式密码的文本框不显示文本 asp.net c#

c# - 将包含驱动器号的相对路径转换为 ​​.NET 文件函数的绝对路径

c# - 更改 HttpPostedFileBase.SaveAs 目标目录