当前位置: 代码迷 >> 综合 >> C#学习(面向过程)Day04——数组、枚举、结构体、字符串
  详细解决方案

C#学习(面向过程)Day04——数组、枚举、结构体、字符串

热度:23   发布时间:2023-12-05 15:51:45.0

1.一维数组、二维数组、冒泡排序及其优化

using System;namespace Day08_1
{class Program{static void Main(string[] args){#region 一维数组/*//特点:可以存多个;并且是相同的数据类型//定义: 数据类型[] 数组名 -----------------------------------------------------数组的定义//int[] ages;   一组年龄//float[] scores;   一组成绩//string[] names;   一组名字//初始化:开辟内存空间    ------------------------------------------------------数组的初始化1.动态初始化:数据类型[] 数组名 = new 数据类型[数组长度]例如:int[] intArray = new intArray[6];数组元素初始为默认值0string[] studentNames = new string[5];各个数据类型的默认值  ------------各个数据类型的默认值整型、浮点型 --> 默认值都是0bool类型 --> 默认值为falsechar类型 --> 默认值为空字符 --> '\0'string类型(代表引用类型) --> 默认值都是null数据类型[] 数组名 = new 数据类型[数组长度]{元素1,元素2,...}例如:int[] intArray = new intArray[6]{0,1,2,...};int[] intArray = new intArray[]{"Tom","Army"};2.静态初始化int[] numbers = {1,2,3,4,5};numbers = new[]{1,1,2,1,1};//数组元素的访问         -------------------------------------------------------数组元素的访问//数组名+下标//例如: array[3]         //数组下标//1.从0开始;    --------------注意不要防止数组越界//2.可以是数字也可以是下标;//3.数组长度array.lengthConsole.WriteLine(numbers.Length);//数组的遍历            ---------------------------------------------------------数组的遍历for (int i = 0; i < numbers.Length; i++){numbers[i]++;Console.WriteLine(numbers[i]);}//数组赋值             ---------------------------------------------------------数组赋值//第一个数字:[3,4,5,6]   第二个数字:[30,31,32,33]float[] scores = new float[20];   //***********----scores存的是数组首地址int aa = 10; //0000 1010 [值类型]存的是具体的值//scores -> 300 [引用类型,字符串例外] --> 对应的值(第一个元素首地址[3])float[] finalScores = scores;finalScores[0] = 100;Console.WriteLine("scores[0]" + scores[0]);*//*//【练习】int[] intArr = {2, 3, 5, 7, 11, 13, 17};//逆向输出数组for (int i = intArr.Length-1; i >= 0; i--){Console.WriteLine(intArr[i]);}//跳跃输出for (int i = intArr.Length-1; i >= 0; i-=2){Console.WriteLine(intArr[i]);}//求数组所有的和int sum = 0;for (int i = 0;i< intArr.Length; i++){sum += intArr[i];}Console.WriteLine(sum);//求数组里的最大最小值int max = intArr[0];int min = intArr[0];for (int i = 1;i < intArr.Length; i++){if (max < intArr[i]){max = intArr[i];}if (min > intArr[i]){min = intArr[i];}}Console.WriteLine("数组最大值是:" + max);Console.WriteLine("数组最小值是:" + min);//两个数组相加,长度不一时,剩余元素取长的元素值int[] array01 = {1, 2, 3, 4, 5, 6, 7, 8, 9};int[] array02 = {12, 45, 67, 89, 332, 11};int max = array01.Length > array02.Length ? array01.Length : array02.Length;int min = array01.Length < array02.Length ? array01.Length : array02.Length;int[] newArray = new int[max];for (int i = 0; i < min; i++){newArray[i] = array01[i] + array02[i];Console.WriteLine(newArray[i]);}for (int i = min; i < max; i++){newArray[i] = array01.Length > array02.Length ? array01[i] : array02[i];Console.WriteLine(newArray[i]);}*/#endregion#region 二维数组/*int[] zsScores = new[] {99, 80, 70, 100, 99};int[] lsScores = new[] {99, 80, 70, 100, 99};int[] wwScores = new[] {99, 80, 70, 100, 99};int[][] class1StudentScores = {zsScores, lsScores, wwScores};int[][] class2StudentScores = {zsScores, lsScores, wwScores};int[][] class3StudentScores = {zsScores, lsScores, wwScores};int[][][] schoolScores = {class1StudentScores, class2StudentScores, class3StudentScores};*//*//.Net 定义的二维数组//--------------------------------------------------------------二维数组的定义//数据类型 [,] 数组名;int [,] studentsScores;//--------------------------------------------------------------二维数组的初始化//1.动态初始化法一:int[,] studentsScores = new int[3,4];法二:studentsScores = new int[3, 4]{{1, 2, 3, 4},{5, 6, 7, 8},{9, 10, 11, 12}};//2.静态初始化int[,] teachersScores ={  {1, 2, 3, 4},  {5, 6, 7, 8},  {9, 10, 11, 12} };//---------------------------------------------------------------二维数组元素的访问//数组名[第一维下标,第二维下标]teachersScores[2,3];注:防止数组越界//---------------------------------------------------------------数组长度Console.WriteLine(teachersScores.Length);                  //1.获取二维总长度Console.WriteLine(teachersScores.GetLength(0));            //2.获取二维中的一维长度Console.WriteLine(teachersScores.GetLength(1));            //3.获取二维中的二维长度//---------------------------------------------------------------数组的遍历//1.for遍历for (int i = 0; i < teachersScores.GetLength(0); i++){for (int j = 0; j <teachersScores.GetLength(1); j++){Console.Write(teachersScores[i,j] + " ");}Console.WriteLine();}//2.foreach遍历  -----------------遍历是只读的,不能写入foreach (var item in teachersScores){Console.Write(item + " ");}*///二维数组和多维数组的比较//最大区别:.Net二维数组,每行的列数必须一致//          多维数组,每行的列数不一致一致//一维数组是  引用类型(存的是地址) 默认值是null//二维数组也是 引用类型(存的是地址) 默认值是null//string也是引用类型,但默认值比较特殊,默认值为空,地址号为0,表示没有地址/*//【练习】//1.将一个二维数组的行和列交换,存储到另一个数组里/*float[,] heroProperties ={{100,20,10,10 },{10,200,100,10 }};float[,] newHeroProperties = new float[4,2];for (int i = 0; i < newHeroProperties.GetLength(0); i++){for (int j = 0; j < newHeroProperties.GetLength(1); j++){newHeroProperties[i, j] = heroProperties[j, i];Console.Write(newHeroProperties[i,j] + " ");}Console.WriteLine();}*///2.找出二维数组中的最大值,并输出所在的行和列/*int[,] numbers ={{100,20,10,10 },{10,200,100,10 }};int  max = numbers[0,0];int x = 0;int y = 0;for (int i = 0; i < numbers.GetLength(0); i++){for (int j = 0; j < numbers.GetLength(1); j++){if (numbers[i, j] > max){max = numbers[i, j];x = i;y = j;}}}Console.WriteLine($"max = {max} ,i = {x},j = {y}");*///3.求二维数组3X3对角线的和/*int[,] number ={{1,2,3},{4,5,6},{7,8,9}};int sum = 0;for (int i = 0; i < number.GetLength(0); i++){for (int j = 0; j < number.GetLength(1); j++){if (i == j || (i + j == 2)){sum = sum + number[i, j];}}}Console.WriteLine(sum);*/#endregion#region 冒泡排序(Bubble sort)及其优化/*int[] numbers = {1, 90, 9, -1, 7};//1, 90, 9, -1, 7//[0] [1] [2] [3] [4]int a = 10, b = 20;//临时变量,初始的a值:10int temp = a;     a = b;b = temp;//赋值给临时变量 temp = numbers[0];  numbers[0] = numbers[3];numbers[3] = temp;//从小到大排序,排序原理//1 < 90,不动   1 , 90, 9, -1, 7//90 > 9,换一下  1,9,90,-1,7//90 > -1,换一下 1,9,-1,90,7//90 > 7,换一下  1,9,-1,7,90//一轮结束,排好90//1 < 9,不动  1,9,-1,7,90//9 >-1,换一下 1 ,-1 ,9,7,90//9 > 7,换一下 1,-1,7,9,90//二轮结束,排好9//1 > -1,换一下 -1 ,1,7,9,90//1 < 7不动//三轮结束,排好7//-1 < 1,不动 -1,1,7,9,90//四轮结束,排好1//全部结束//numbers.length   数组长度//numbers.length - 1   排序轮次for (int i = 0; i < numbers.Length - 1; i++){bool complete = true;         //----冒泡排序的优化如果没有发生交换,直接跳出//numbers.length - i - 1  比较的次数for (int j = 0; j < numbers.Length - i - 1; j++){//从小到大排序//if (numbers[j] > numbers[j + 1])//从大到小排序//if (numbers[j] < numbers[j + 1])if (numbers[j] > numbers[j + 1]){//排序还没完成complete = false;//临时变量int temp = numbers[j];numbers[j] = numbers[j+1];numbers[j+1] = temp;}}if(complete)break;}//排序完成,验证结果for (int i = 0; i < numbers.Length; i++){Console.WriteLine(numbers[i]);}//思考,如果数组提前完成,剩下的轮次不需要进行,对于这个问题该如何优化呢?*/#endregion#region 访问修饰符//限制程序员,提高代码安全性//程序集//程序集//命名空间//命名空间/结构体///方法///方法/类///方法///方法#endregion}}
}

2.枚举,结构体

using System;namespace Day08_2
{class Program{enum EquipType{Helmet,   //头盔     默认0BodyArmor, // 防弹衣Knapsack,  // 背包}enum GameState{StartGame,   //游戏开始PauseGame,   //游戏暂停GaveOver     //游戏结束}enum Weapon{Rifle,   //步枪MachineGun,  //机关枪Saber,   //军刀}enum Phone{Market = 900,HumanResouse = 400,Defent}struct Student{public string name;public  char sex;public  byte age;public string phone;public float[] scores;//构造函数(方法)//方法名称必须和构造体名称保持一致public Student(string _name,byte _age,char _sex,string _phone,float[] _scores){name = _name;sex = _sex;age = _age;phone = _phone;scores = _scores;}}static void Main(string[] args){#region 枚举类型(自定义类型)/*//以前//缺点:可读性不高,可维护性差,易出错//0 --- 头盔//1 --- 防弹衣//2 --- 背包int equipType = 0;equipType = 2;string str_equipType = "头盔";str_equipType = "防弹衣";str_equipType = "背包";//现在自定义枚举类型//1.定义//enum 枚举类型名{枚举值1,枚举值2......}//例如:enum EquipType   定义的装备类型//{//     Helmet,   头盔//     BodyArmor,  防弹衣//     Knapsack,   背包//}//2.使用枚举类型EquipType myEquip = EquipType.Helmet;myEquip = EquipType.Knapsack;myEquip = EquipType.BodyArmor;//3.将枚举类型强制转换为整型int et = (int) myEquip;//4.*/#endregion#region 结构体(自定义类型)/*//结构体是一个值类型//包含很多值,不能有初值//结构体声明//struct Student{     //   pubilc string name;//   public  char sex;//   public  byte age;//   public string phone;//   public float[] scores;//  }//声明一个结构体变量Student xiaoming;//给结构体赋值xiaoming.name = "小明";xiaoming.age = 15;xiaoming.sex = 'M';xiaoming.phone = "12345678910";xiaoming.scores = new float[]{100,99,98};//结构体的构造函数Student xiaohong = new Student("小红",18,'F',"12345678901",new float[] {100, 100, 100});//结构体是值类型xiaohong = xiaoming;xiaohong.name = "小红";Console.WriteLine(xiaohong.name);//如何管理很多学生//如何管理很多数字*/#endregion}}
}

3.字符串 

using System;namespace Day10_2
{class Program{static void Main(string[] args){#region 字符串//字符串有一个缓存池//每次赋值都会开辟新空间string str = "abcdf";str += "hi";   //+=//缺点:会生成垃圾,回收也很耗性能//字符串当字符数组用Console.WriteLine(str[0]);  //只能读不能写//将字符串转成字符数组再进行修改char[] chars = str.ToCharArray(); //字符串转成字符数组chars[0] = '1';str = "adsahdhsgahfdgsahgdahgdhadgsahgda";//API学习手册//1.compare--比较字符串的内容,判断字符串某些字符是否相等//2.Contains--返回一个值,该值只是指定的子串是否出现在字符串中string msg = "你好妈?";bool contains = msg.Contains('妈');            //判断该字符中是否出现‘妈’Console.WriteLine(contains);//3.Remove--返回指定数量字符在当前这个实例起始点在已删除的指定的位置的新字符串string address = "北京市海淀区";address = address.Remove(3);        //把第三个字符及后面的都删掉,是返回一个新字符串,并没有修改原来的字符串//address = address.Remove(3, 3);  Console.WriteLine(address);//4.IndexOf--定位字符串中第一次出现某个给定子字符串或字符的位置int index = str.IndexOf('s');       Console.WriteLine(index);int indexof = str.LastIndexOf('s');Console.WriteLine(indexof);//5.LastIndexOf--与IndexOf一样,但定位最后一次出现的位置//6.IndexOfAny--定位字符串中第一次出现某个字符或一组字符的位置//7.LastIndexOfAny--与IndexOfAny一样,但定位最后一次出现的位置//8.Format--格式化包含各种值的字符串和如何格式化每个值的说明符//9.Insert--把一个字符串实例插入到另一个字符串实例的指定索引处//10.Replace--用另一个字符或子字符串替换字符串中给定的字符或子字符串//11.CopyTo--把从选定的下标开始的特定数量的字符复制到数组的一个全新实例中//12.Concat--把多个字符串实例合并为一个实例//13.PadLeft--该字符串通过在此实例中的字符左侧填充空格来达到指定的总长度,从而实现右对齐//14.Padright--该字符串通过在此实例中的字符右侧填充空格来达到指定的总长度,从而实现左对齐//15.ToLower--把字符串转换为小写形式//16.ToUpper--把字符串转换为大写形式//17.Join--合并字符串数组,创建一个新的字符串//18.Split--在出现给定字符的地方,把字符串拆分为一个子字符串数组//19.Substring--在字符串中检索给定位置的子字符串//20.Trim--删除首尾的空白#endregion#region 转义字符\char myChar = '\'';Console.WriteLine(myChar);string myStr = "\'\'\"";Console.WriteLine(myStr);myStr = "aaa\naaaa"; //换行==回车Console.WriteLine(myStr);myStr = "aaa\taaaa\t"; //Tab键的空间Console.WriteLine(myStr);myChar = '\\';      //打印反斜杠Console.WriteLine(myChar);#endregion}}
}

4.作业

using System;namespace Day08_3
{class Program{enum GameState{GameStart = 1, //游戏开始GamePause = 2, //游戏暂停GameOver = 0,  //游戏结束}/// <summary>/// 第五题用到的结构体/// </summary>struct HeroWeapon{public string name;public int damageBonus;public int spellStrengthBonus;public int HPBonus;/// <summary>/// 构造函数/// </summary>/// <param name="_name"></param>/// <param name="_damageBonus"></param>/// <param name="_spellStrengthBonus"></param>/// <param name="_hpBonus"></param>public HeroWeapon(string _name, int _damageBonus, int _spellStrengthBonus, int _hpBonus)    {name = _name;damageBonus = _damageBonus;spellStrengthBonus = _damageBonus;HPBonus = _hpBonus;}}/// <summary>/// 第六题用到的枚举和结构体/// </summary>enum Type{consumables ,  //消耗品equipment ,    //装备weapon ,       //武器materials     //材料}struct Item{public string name;        //物品名称public float buyingPrice;  //买入价格public float solingPrice;  //卖出价格public Type type;/// <summary>/// 构造函数/// </summary>/// <param name="_name"></param>/// <param name="_buyingPrice"></param>/// <param name="_solingPrice"></param>/// <param name="_type"></param>public Item(string _name, float _buyingPrice, float _solingPrice,Type _type)  //---构造函数中引用枚举参数{name = _name;buyingPrice = _buyingPrice;solingPrice = _solingPrice;type = _type;}}/// <summary>/// 第七题用到的枚举和结构体/// </summary>enum HeroType{master,   //法师warrior,  //战士assassin, //刺客tank,     //坦克assist,   //辅助shooter  //射手}struct Hero{public string name;public Item[] items;public HeroType type;/// <summary>/// 构造函数/// </summary>/// <param name="_name"></param>/// <param name="_items"></param>/// <param name="_type"></param>/*public Hero(string _name,Item[] _items, HeroType _type){name = _name;items = _items;type = _type;}*/public Hero(string name, Item[] items, HeroType type){this.name = name;this.items = items;this.type = type;}}static void Main(string[] args){#region 第一题/*//有?个3?4列的?维数组,要求编程找出最?元素,并输出所在的?和列。int[,] numbers ={{100,20,10,10 },{10,200,100,10 },{1,2,1000,4}};int  max = numbers[0,0];int x = 0;int y = 0;for (int i = 0; i < numbers.GetLength(0); i++){for (int j = 0; j < numbers.GetLength(1); j++){if (numbers[i, j] > max){max = numbers[i, j];x = i;y = j;}}}Console.WriteLine($"max = {max} ,i = {x},j = {y}");*/#endregion#region 第二题/*//求?维数组(3?3列)的对?线元素之和。int[,] number ={{1,2,3},{4,5,6},{7,8,9}};int sum = 0;for (int i = 0; i < number.GetLength(0); i++){for (int j = 0; j < number.GetLength(1); j++){if (i == j || (i + j == 2)){sum = sum + number[i, j];}}}Console.WriteLine(sum);*/#endregion#region 第三题/*//string str = “Hello,QianFeng!Hello,Unity!”;//?foreach遍历字符串,求字符串中包含?个n 字符。string str = "Hello,QianFeng!Hello,Unity!";int count = 0;foreach (var item in str)                //--------用foreach循环{if (item == 'n'){count++;}}Console.WriteLine(count);char[] chars = str.ToCharArray();      //------------字符串转换成字符数组for (int i = 0; i < chars.Length; i++)   //---------字符数组长度{if (chars[i] == 'n'){count++;}}*/#endregion#region 第四题//创建枚举表示游戏的所有状态(1表示开始游戏,2表示暂停游戏,0表示结束游戏)//在上面#endregion#region 第五题/*//创建英雄装备结构体,包含名称,攻击?加成,法术强度加成,?量加成//   有5个装备保存在结构体数组当中,编程找出?量加成最?者                --------------------如何给结构体数组赋值??????????????//   对装备数组按照攻击?加成排序并使装备按照攻击?加成升序进?信息打印HeroWeapon[] weapons = new HeroWeapon[5];weapons[0] = new HeroWeapon("电刀", 170, 180, 150);weapons[1] = new HeroWeapon("三项之刃",120,80,60);weapons[2] = new HeroWeapon("破军", 170, 140, 190);weapons[3] = new HeroWeapon("无尽之刃",120,700,60);weapons[4] = new HeroWeapon("暗影战斧", 170, 190, 100);int HPBonusMax = weapons[0].HPBonus;int flag = 0;for (int i = 1; i < weapons.Length; i++){if (weapons[i].HPBonus>HPBonusMax){HPBonusMax = weapons[i].HPBonus;flag = i;}}Console.WriteLine(weapons[flag].name);int max = weapons[0].damageBonus;HeroWeapon temp = new HeroWeapon();for (int i =  0; i < weapons.Length-1; i++){for (int j = 0; j < weapons.Length-i-1; j++){if (weapons[j].damageBonus>weapons[j+1].damageBonus){temp = weapons[j];weapons[j] = weapons[j + 1];weapons[j + 1] = temp;}}}for (int i = 0; i < weapons.Length; i++){Console.WriteLine($"{weapons[i].name},{weapons[i].damageBonus},{weapons[i].spellStrengthBonus},{weapons[i].HPBonus}");}*/#endregion#region 第六题//创建物品结构体Item,该结构体包含结构体成员:物品名称,物品买?价格,物品卖出价//格,物品的类型(包括包含消耗品,装备,武器,材料,使?枚举)。给该结构体定义构造函//数,在物品创建的时候给物品的属性赋值,使?我们定义的结构体创建出3个物品。Item[] item = new Item[3];item[0] = new Item("血药",100,120,(Type)0);  //将整型强制转换成枚举类item[1] = new Item("手枪",150,200,(Type)1);item[2] = new Item("护甲",100,110,(Type)2);/*for (int i = 0; i < item.Length; i++){Console.WriteLine($"{item[i].name},{item[i].buyingPrice},{item[i].solingPrice},{item[i].type}");}*/#endregion#region 第七题//创建英雄结构体Hero,包含字段:名字name,加装的物品items(数组类型),英雄的类型//(类型分为:法师,战?,刺客,坦克,射?,辅助,使?枚举)。利?该结构体创建出英//雄,加装上?创建的三个物品Hero  newHero = new Hero("后裔",item,(HeroType)5);Console.WriteLine($"{newHero.name}");for (int i = 0; i < item.Length; i++){Console.WriteLine($"{item[i].name},{item[i].buyingPrice},{item[i].solingPrice},{item[i].type}");}Console.WriteLine($"{(HeroType)5}");#endregion}}
}