AI智能
改变未来

C#入门第八课


数组

值类型:
int,bool,枚举,结构体

引用类型:
字符串,数组

数组在栈中存地址,堆中放内容。

排序方式

冒泡排序

int[] a = { 3, 5, 2, 4, 6, 0, 1 };for(int i=0;i<a.Length - 1; i++){for(int j=0;j<a.Length - i - 1; j++){if (a[j] > a[j + 1]){int tmp = a[j];a[j] = a[j + 1];a[j + 1] = tmp;}}}for(int i = 0; i < a.Length; i++){Console.Write(a[i]+\" \");}

选择排序

int[] a = { 5, 1, 3, 2, 0 };for(int i=0;i<a.Length - 1; i++){int q = i;int num = a[i];for(int j = i + 1; j < a.Length; j++){if (num > a[j]){q = j;num = a[j];}}int tmp = a[i];a[i] = num;a[q] = tmp;}for(int i = 0; i < a.Length; i++){Console.WriteLine(a[i]);}

插入排序

int[] a = { 5, 1, 3, 2, 0 };for(int i = 0; i < a.Length-1; i++){for(int j = i+1; j>0; j--){if (a[j] < a[j - 1]){int tmp = a[j];a[j] = a[j - 1];a[j - 1] = tmp;}}}for(int i = 0; i < a.Length; i++){Console.WriteLine(a[i]);}

二维数组

类型[,]数组名=new 雷星[常量表达式1,常量表达式2];
寻找最大值

int[,] td = new int[3, 4] {{2,25,6,8},{40,12,30,16},{18,20,22,24}};int num = td[0, 0];for (int i = 0; i < 3; i++){for (int j = 0; j < 4; j++){if (num < td[i, j]){num = td[i, j];}}}Console.WriteLine(num);

foreach的用法

查找字符串中某个字母的个数

string str = \"sfsgfgergqerr\";int sum = 0;foreach (char x in str){if (x == \'s\'){sum++;}}Console.WriteLine(sum);

数组所有元素之积

int[] a = new int[5] { 1, 2, 2, 4, 5 };int sum = 1;foreach (int x in a){sum = sum * x;}Console.WriteLine(sum);
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » C#入门第八课