c#基础04(数组)
数组
数组的基本要素
标识符:数组的名称,用于区分不同的数组
元素:向数组中存放的数据
类型:元素的数据类型
下标:元素的编号,从0开始
数组声明同时初始化
static void Main(string[] args)
{
int[] netScore1 = new int[3] { 78, 28, 90 };//方括号中的数字决定数组长度
int[] netScore2 = new int[] { 78, 28, 90 };//数组元素直接决定长度
int[] netScore3 = { 78, 28, 90 };
}
static void Main(string[] args)
{//数组求和,以及平均值
int sumScore = 0;
int[] score = new[]{12,34,90,30};
for (int i= 0; i < score.Length; i++)
{
sumScore += score[i];
}
double avgScore = sumScore / score.Length;
Console.WriteLine(sumScore);
Console.WriteLine(avgScore);
Console.ReadLine();
}
foreach 循环结构
//语法
foreach(元素类型 变量名 in集合或者数组名){
//语句
}
//案例
static void Main(string[] args)
{
int sumScore = 0;
int[] score = new[]{12,34,90,30};
foreach (int eachscore in score)
{
sumScore += eachscore;
}
double avgScore = sumScore / score.Length;
Console.WriteLine(sumScore);
Console.WriteLine(avgScore);
Console.ReadLine();
}
字符串分割和重新组合的方法
string str1 = "小红,小白,小马";
//字符串分割split()
string[] a = str1.Split(',');
//字符串重新组合join()
string nameList = string.Join("_", a);
Console.WriteLine(nameList);
Console.ReadLine();