首页 > 编程语言 > 详细

C#删除数组元素

时间:2020-06-03 09:55:48      阅读:32      评论:0      收藏:0      [点我收藏+]
 1 using System;
 2 
 3 namespace ConsoleApp1
 4 {
 5     class Program
 6     {
 7         /// <summary>
 8         /// 删除数组元素
 9         /// </summary>
10         /// <param name="arrayBorn">源数组</param>
11         /// <param name="index">索引</param>
12         /// <param name="Len">删除长度</param>
13         static string[] DeleteEle(string[] arrayBorn,int index,int Len) 
14         {
15             if (Len < 0)    //删除长度小于0,返回
16             {
17                 return arrayBorn;
18             }
19             if ( (index + Len) > arrayBorn.Length)      //删除长度超出数组范围 
20             {
21                 Len = arrayBorn.Length - index;         //将长度设置为能删除的最大长度
22             }
23             for (int i = 0;i < arrayBorn.Length - ( index + Len); i++)      //将删除元素后面的元素往前移动
24             {
25                 if ((index + i + Len) > arrayBorn.Length)       //若删除元素+删除长度超过数组的范围,即无法从数组中找到移动元素,则用null替代
26                 {
27                     arrayBorn[index + i] = null;
28                 }
29                 else            //若能用数组的元素替换则用数组中的元素
30                 {
31                     arrayBorn[index + i] = arrayBorn[index + i + Len];
32                 }           
33             }
34             /*不改变数组长度*/
35             for (int j =Len;j > 0; j--)         //将删除元素后多余的元素置为null值
36             {
37                 arrayBorn[arrayBorn.Length - j ] = null;
38             }
39             return arrayBorn;            
40             /*改变数组长度
41             string[] newArray = new string[arrayBorn.Length-Len];
42             for (int j =0;j < newArray.Length;j++) 
43             {
44                 newArray[j] = arrayBorn[j];
45             }
46             return newArray;
47             */
48         }
49         static void Main(string[] args)
50         {
51             string[] arrayString = new string[] { "0","1","2","3","4","5"};
52             Console.WriteLine("原数组元素:");
53             foreach (string i in arrayString)
54             {
55                 Console.Write(i + " ");
56             }
57             Console.WriteLine();
58             arrayString = DeleteEle(arrayString, 1, 3);
59             Console.WriteLine("删除元素后的数组");
60             foreach (String i in arrayString)
61             {
62                 Console.Write(i + " ");
63             }
64         }
65     }
66 }

 

C#删除数组元素

原文:https://www.cnblogs.com/kyuusan/p/13034908.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!