1.合并拆分数组
/// <summary> /// 合并数组 /// </summary> /// <param name="First"> 第一个数组 </param> /// <param name="Second"> 第二个数组 </param> /// <returns> 合并后的数组(第一个数组+第二个数组,长度为两个数组的长度) </returns> public string[] MergerArray( string[] First, string[] Second) { string[] result = new string[First.Length + Second.Length]; First.CopyTo(result, 0); Second.CopyTo(result, First.Length); return result; } /// <summary> /// 数组追加 /// </summary> /// <param name="Source"> 原数组 </param> /// <param name="str"> 字符串 </param> /// <returns> 合并后的数组(数组+字符串) </returns> public string[] MergerArray( string[] Source, string str) { string[] result = new string[Source.Length + 1]; Source.CopyTo(result, 0); result[Source.Length] = str; return result; } /// <summary> /// 从数组中截取一部分成新的数组 /// </summary> /// <param name="Source"> 原数组 </param> /// <param name="StartIndex"> 原数组的起始位置 </param> /// <param name="EndIndex"> 原数组的截止位置 </param> /// <returns></returns> public string[] SplitArray( string[] Source, int StartIndex, int EndIndex) { try { string[] result = new string[EndIndex - StartIndex+ 1]; for ( int i = 0; i <= EndIndex - StartIndex; i++) result[i] = Source[i+StartIndex]; return result; } catch (IndexOutOfRangeException ex) { throw new Exception(ex.Message); } } /// <summary> /// 不足长度的前面补空格,超出长度的前面部分去掉 /// </summary> /// <param name="First"> 要处理的数组 </param> /// <param name="byteLen"> 数组长度 </param> /// <returns></returns> public string[] MergerArray( string[] First, int byteLen) { string[] result; if (First.Length > byteLen) { result = new string[byteLen]; for ( int i = 0; i < byteLen; i++) result[i] = First[i + First.Length - byteLen]; return result; } else { result = new string[byteLen]; for ( int i = 0; i < byteLen; i++) result[i] = " "; First.CopyTo(result, byteLen-First.Length); return result; } }
2.调用
string[] student1 = { " a ", " b ", " c ", " d ", " e ", " f "}; string[] student2 = { " 0 ", " 1 ", " 2 ", " 3 ", " 4 ", " 5 ", " 6 ", " 6 ", " 1 ", " 8 ", " 16 ", " 10 ", " 45 ", " 37 ", " 82 " }; string student3 = " Test "; // 两个数组相加 结果--> { "a", "b", "c", "d", "e", "f","0", "1", "2", "3", "4", "5", "6", "6", "1", "8", "16", "10", "45", "37", "82" }; string[] Merger1 = MergerArray(student1, student2); // 数组+字符串 结果-->{ "a", "b", "c", "d", "e", "f","Test"}; string[] Merger2 = MergerArray(student1, student3); // 不足10位的,前面补空格 结果-->{" ", " ", " ", " ", "a", "b", "c", "d", "e", "f"}; string[] Merger3 = MergerArray(student1, 10); // 超过3位的,只取最后3后 结果-->{"d", "e", "f"}; string[] Merger4 = MergerArray(student1, 3); // 截取部分数组 结果-->{"c", "d", "e"}; string[] SplitArray1 = SplitArray(student1, 2, 4);