c# 从零到精通 数组的操作-向一维数组添加一个数组,遍历数组内容

c# 从零到精通 数组的操作-向一维数组添加一个数组,遍历数组内容
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AddArrays
{
class Program
{
///
/// 向一维数组中添加一个数组
///
/// 源数组
/// 要添加的数组
/// 添加索引
/// 新得到的数组
static int[] AddArray(int[] ArrayBorn, int[] ArrayAdd, int Index)
{
if (Index >= (ArrayBorn.Length))//判断添加索引是否大于数组的长度
Index = ArrayBorn.Length - 1;//将添加索引设置为数组的最大索引
int[] TemArray = new int[ArrayBorn.Length + ArrayAdd.Length];//声明一个新的数组
for (int i = 0; i < TemArray.Length; i++)//遍历新数组的元素
{
if (Index >= 0)//判断添加索引是否大于等于0
{
if (i < (Index + 1))//判断遍历到的索引是否小于添加索引加1
TemArray[i] = ArrayBorn[i];//交换元素值
else if (i == (Index + 1))//判断遍历到的索引是否等于添加索引加1
{
for (int j = 0; j < ArrayAdd.Length; j++)//遍历要添加的数组
TemArray[i + j] = ArrayAdd[j];//为遍历到的索引设置添加值
i = i + ArrayAdd.Length - 1;//将遍历索引设置为要添加数组的索引最大值
}
else
TemArray[i] = ArrayBorn[i - ArrayAdd.Length];//交换元素值
}
else
{
if (i == 0)//判断遍历到的索引是否为0
{
for (int j = 0; j < ArrayAdd.Length; j++)//遍历要添加的数组
TemArray[i + j] = ArrayAdd[j];//为遍历到的索引设置添加值
i = i + ArrayAdd.Length - 1;//将遍历索引设置为要添加数组的索引最大值
}
else
TemArray[i] = ArrayBorn[i - ArrayAdd.Length];//交换元素值
}
}
return TemArray;//返回添加数组后的新数组
}
static void Main(string[] args)
{
int[] ArrayInt = new int[] { 0, 1, 2, 3, 8, 9 };//声明一个数组,用来作为源数组
int[] ArrayInt1 = new int[] { 4, 5, 6, 7 };//声明一个数组,用来作为要添加的数组
Console.WriteLine(“源数组:”);
foreach (int i in ArrayInt)//遍历源数组
Console.Write(i+" ");//输出源数组元素
Console.WriteLine();//换行
Console.WriteLine(“要添加的数组:”);
foreach (int i in ArrayInt1)//遍历要添加的数组
Console.Write(i + " “);//输出要添加的数组中的元素
Console.WriteLine();//换行
ArrayInt = AddArray(ArrayInt, ArrayInt1, 3);//向数组中添加数组
Console.WriteLine(“添加后的数组:”);
foreach (int i in ArrayInt)//遍历添加后的数组
Console.Write(i+” ");//输出添加后的数组中的元素
Console.ReadLine();
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DK业

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值