C#数组(小练习)
练习1:从一个整数数组中取出最大的整数
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 练习 { class Program { static void Main(string[] args) { //从一个整数数组中取出最大的整数 int[] numbers = { 3, 5, 6, 37, 19, 98, 65, 34, 54, 43 }; int max = numbers[0]; int min = numbers[0]; for (int i = 0; i < numbers.Length; i++) { if (numbers[i] > max) { max = numbers[i]; } if (numbers[i] < min) { min = numbers[i]; } } Console.WriteLine("max={0},max={1}", max, min); Console.ReadKey(); } } }
练习2:计算一个整数数组的所有元素的和。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 练习 { class Program { static void Main(string[] args) { //计算一个整数数组的所有元素的和 int[] numbers = { 3, 5, 6, 37, 19, 98, 65, 34, 54, 43 }; int sum = 0; for (int i = 0; i < numbers.Length; i++) { //sum =sum+numbers[i]; sum += numbers[i]; } Console.WriteLine("sum=" + sum);//sum=364 Console.ReadKey(); } } }练习3:将一个字符串数组输出为|分割的形式,比如“梅西|卡卡|郑大世”
方法一:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 练习 { class Program { static void Main(string[] args) { //将一个字符串数组输出为|分割的形式,比如“梅西|卡卡|郑大世” string[] names = { "梅西", " 卡卡", " 郑大世" }; string str = ""; for (int i = 0; i < names.Length; i++) { if (i == names.Length - 1)//循环到数组的最后一个元素 不需要加| { str = str + names[i]; } else { str = str + names[i] + "|";//循环后加两个元素之间 | } } Console.WriteLine(str); Console.ReadKey(); } } }方法二:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 练习 { class Program { static void Main(string[] args) { //将一个字符串数组输出为|分割的形式,比如“梅西|卡卡|郑大世” string[] names = { "梅西", " 卡卡", " 郑大世" }; string str = ""; for (int i = 0; i < names.Length; i++) { if (i == names.Length - 1) { break;//循环到最后一个元素跳出 } str = str + names[i] + "|"; } str = str + names[names.Length - 1];//加上最后一个元素 Console.WriteLine(str); Console.ReadKey(); } } }练习4:将一个字符串数组的元素的顺序进行反转。{“3”,“a”,“8”,“haha”} {“haha”,“8”,“a”,“3”}。第i个和第length-i-1个进行交换。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 练习 { class Program { static void Main(string[] args) { // 将一个字符串数组的元素的顺序进行反转。{“3”,“a”,“8”,“haha”} //{“haha”,“8”,“a”,“3”}。第i个和第length-i-1个进行交换。 string[] str = { "haha", "8", "a", "3" }; //反序输出 for (int i = str.Length - 1; i >= 0; i--) { Console.WriteLine(str[i]); } Console.WriteLine("======="); //交换反转 string temp; for (int i = 0; i < str.Length / 2; i++) { //第i个元素和length-1-i个元素 temp = str[i]; str[i] = str[str.Length - 1 - i]; str[str.Length - 1 - i] = temp; } for (int i = 0; i < str.Length; i++) { Console.WriteLine(str[i]); } Console.ReadKey(); } } }
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: tp 单字母函数详解
- 下一篇: tp框架 一个简单的函数 使用I()获取get和post