第十一講:字符串
一、string是一種特殊的引用類型,使用起來好像值類型
例:class Program
{
static void Main(string[] args)
{
string s = "123";
string k = s;
k = "456";
Console.WriteLine(s);
}
}
結果:123
二、string中部分函數的意思trim除去空格 ToUpper把字母轉換爲大寫 Split分割
例:class Program
{
static void Main(string[] args)
{
string str = " 123456";
Console.WriteLine(str);
Console.WriteLine(str.Trim());
}
}
結果: 123456
123456
第十二講:數組
一、Array:在.NET中全部的數組都是繼承在Array下的,是引用類型,不可以直接定義。實例化的時候不能夠用new關鍵字。屬於抽象類,能夠被子類實例化。
例:static void Main(string[] args)
{
Array arr = Array.CreateInstance(typeof(int), 10);
for (int i = 0; i < 10; i++)
{
arr.SetValue(i * 2, i);
}
foreach (int i in arr)
{
Console.WriteLine(i);
}
for (int i = 0; i < 10; i++)
{
Console.WriteLine(arr.GetValue(i));
}
}
二、一維數組:int[] arrint=new int[10]
(1)Array方法有Sort排序
例:class Program
{
static void Main(string[] args)
{
int[] arri = new int[] { 2, 35, 1, 3, 53, 216, 1 };
Array.Sort(arri);
int len=arri.Length;
for (int i = 0; i < len; i++)
{
Console.WriteLine(arri[i]);
}
}
}
結果:1
1
2
3
35
53
216c++
(2)Array方法中的Reverse方法表示反轉
例:static void Main(string[] args)
{
int[] arri = new int[] { 2, 35, 1, 3, 53, 216, 1 };
Array.Sort(arri);
Array.Reverse(arri);
int len=arri.Length;
for (int i = 0; i < len; i++)
{
Console.WriteLine(arri[i]);
}
}
結果:216
53
35
3
2
1
1
三、二維數組定義:int[,] arri=new int[i,j];
int[,] arri = new int[,] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
例:int[,] arri = new int[,] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
for (int r = 0; r < 2; r++)
{
for (int c = 0; c < 4; c++)
{
Console.WriteLine(arri[r,c]);
}
}
四、交錯數組:數組中的數組 定義:int[][] arri=new int[2][];不容許有第二個方括號的值的不容許有列
例: int[][] arri = new int[3][];
arri[0] = new int[] { 1, 2 };
arri[1] = new int[] { 3};
arri[2]=new int[]{4,5,6};
int rlen = arri.Length;
for (int i = 0; i < rlen; i++)
{
int clen = arri[i].Length;
for (int j = 0; j < clen; j++)
{
Console.WriteLine(arri[i][j]);
}
}
//foreach (int[] i in arri)
//{
// foreach (int j in i)
// {
// Console.WriteLine(j);
// }
//}
foreach和for循環的結果同樣都爲:
1
2
3
4
5
6
也能夠打印單個元素:Console.WriteLine(arri[2][2]);打印結果爲6.
五、用數組寫學生管理系統
例:namespace Chapter12Demo2
{
class Program
{
static void Main(string[] args)
{
string [,] arri=new string[3,3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (j == 0)
{
Console.WriteLine("請輸入學生的姓名:");
arri[i,j] = Console.ReadLine();
}
else if (j == 1)
{
Console.WriteLine("請輸入年齡:");
arri[i,j] = Console.ReadLine();
}
else
{
Console.WriteLine("請輸入性別:");
arri[i,j] = Console.ReadLine();
}
}數組
}
for (int i = 0; i <3; i++)
{
for (int j = 0; j <3; j++)
{
Console.Write(arri[i,j]);
}
Console.WriteLine();
}
}
}
}
ide