练习一:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace _数组练习01 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 string str = null; 14 string[] names = { "老杨","老李","老赵","老孙","老沈"}; 15 for (int i = 0; i < names.Length; i++) 16 { 17 str += names[i] + "|"; 18 } 19 Console.WriteLine(str); 20 Console.ReadKey(); 21 } 22 } 23 }
优化为:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace _数组练习01 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 string str = null; 14 string[] names = { "老杨","老李","老赵","老孙","老沈"}; 15 for (int i = 0; i < names.Length-1; i++) 16 { 17 str += names[i] + "|"; 18 } 19 Console.WriteLine(str+names[names.Length-1]); 20 Console.ReadKey(); 21 } 22 } 23 }
练习二:如遇正数,将这个位置元素的值加1,如遇负数,将这个位置元素的值减1,如遇0,则不变。
int nums={0,5,-8,-41,5,94,-1,-22};
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace _数组练习01 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 int[] nums = { 66,58,841,-556,-121,-541,55}; 14 for (int i = 0; i < nums.Length; i++) 15 { 16 if (nums[i] > 0) 17 { 18 nums[i] += 1; 19 } 20 else if (nums[i] < 0) 21 { 22 nums[i] -= 1; 23 } 24 } 25 for (int i = 0; i < nums.Length; i++) 26 { 27 Console.WriteLine(nums[i]); 28 } 29 Console.ReadKey(); 30 } 31 } 32 }
联系三:将一个字符串数组的元素顺序进行反转
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace _数组练习01 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 string[] names = { "a", "b", "c" ,"d"}; 14 for (int i = 0; i <names.Length/2; i++) 15 { 16 //交换两个变量最简单的方式就是声明第三方的一个变量。 17 string _temp = names[i]; 18 names[i] = names[names.Length - 1 - i]; 19 names[names.Length - 1 - i] = _temp; 20 } 21 for (int i = 0; i < names.Length; i++) 22 { 23 Console.WriteLine(names[i]); 24 } 25 Console.ReadKey(); 26 } 27 } 28 }