# C# Console 基礎語法 ## String 字串處理 1. ```Replace``` 替換子字串 * ```Replace("搜尋字串","替換字串")``` ```csharp= address.Replace(".","[.]"); ``` 2. ```Trim``` 移除字元/空白 * 字元 ```Trim('字元')``` * 空白 ```Trim()``` | 函數 | 移除範圍 | | -------- | -------- | | Trim() | 開頭、結尾 | | TrimStart() | 開頭 | | TrimEnd() | 結尾 | 3. ```IndexOf``` 搜尋 字串/元 位置 * 第一次 ```IndexOf("字串")``` * 最後一次 ```LastIndexOf("字串")``` ```csharp= haystack.IndexOf(needle); ``` 4. ```Substring``` 取出子字串 * ```Substring(起始位置)``` * ```Substring(起始位置,總數量)``` * 範例: ```abc123``` | 函數 | 取得範圍 | 範例 | | -------- | -------- | -------- | | Substring(2)| 從2開始取到結尾 |c123 | | Substring(0,2)| 從0開始,共取2個|ab | | Substring(1,3)| 從1開始,共取3個|bc1| 5. ```Contains``` 是否包含指定字串 ```csharp= str.Contains("搜尋字串"); ``` 6. ```new string``` 建立字串 1. 建立5個```A``` ```csharp= string s=new string('A',5); ``` 2. ```char``` 陣列轉 ```string``` 字串 * 所有 ```csharp= char[] ch_arr={'h','e','l','l','o'} string s=new string(ch_arr) ``` * 指定範圍 * 取得0~2的字元->```hel``` ```csharp= char[] ch_arr={'h','e','l','l','o'} string s=new string(ch_arr,0,3) ``` 3. 快速顛倒順序 * 把```char Array```轉換為```String``` ```csharp= r = new string(r.Reverse().ToArray()); ``` 7. ```Join``` 組合字串 ```csharp= string.Join(" ",list) ``` 8. ```Split()``` 分割 * 單一字元 * 使用空白分割 ```csharp= .Split(' ') ``` * 字串 * 使用 ```"], ["```分割 ```csharp= .Split(new string[] { "], [" }, StringSplitOptions.None) ``` 9. 索引值取出字元 * string ```s=123``` ```csharp= char c=s[0];//從左邊開始,輸出1 ``` ## Math 數學函數 1. ```Sqrt``` 根號數值 * 例如: ```Math.Sqrt(81)``` -> ```9``` ```csharp= Math.Sqrt(81); ``` 2. ```Abs``` 絕對值 * 例如: ```Math.Abs(-17)``` -> ```17``` ```csharp= Math.Abs(-17); ``` 3. ```Pow``` 次方 * 例如: ```Math.Pow(8,2)``` -> ```64``` ```csharp= Math.Pow(8,2); ``` 4. ```Ceiling``` 無條件進位 * 例如: ```Math.Ceiling(3.2)``` -> ```4.0``` ```csharp= double result1 = Math.Ceiling(3.2); ``` ## Dictionary Map 1. 建立 * ```Dictionary<Key類別,Value類別>``` ```csharp= Dictionary<String,int> map = new Dictionary<String,int>(); ``` * 初始化 * 用```{}```將每組Key、Value```{}```包起 * 每組值使用 ```{Key,Value}``` 新增 ```csharp= var dict =new Dictionary<char, int>() { { 'a',1},{ 'b',2},{ 'c','3'} }; ``` 2. 新增Key ```csharp= map[Key] = Value; 3. 修改 Value * Value 次數 +1 ```csharp= map[Key]++; ``` 4. 判斷Key 是否存在 ```csharp= if (map.ContainsKey("文字")){ //執行 } ``` 5. 依照Value數值排序 * 由大到小 -> 使用 ```OrderByDescending``` ```csharp= var dict2 = dict.OrderByDescending(x => x.Value); ``` 6. 使用Value取得Key LINQ * ```FirstOrDefault(列=>列.Value==條件值).Key``` ```csharp= char key=dict.FirstOrDefault(x=>x.Value==row).Key; ``` ## HashSet * 建立 ```csharp= HashSet<int> arr=new HashSet<int>(); ``` * 新增值 ```csharp= arr.Add(1); ``` * 刪除值 ```csharp= arr.Remove(); ``` * 判斷是否存在 ```csharp= bool hasOne = arr.Contains(1); // 回傳true ``` ## ListNode 操作 1. 架構 * ```.next``` 類別為 ```ListNode``` * ```.val``` 值類別為 ```int``` * ```()``` 內為初始化 * ```{}``` 內為 ```new ListNode(參數)``` ```csharp= public class ListNode { public int val; public ListNode next; public ListNode(int val = 0, ListNode next = null) { this.val = val; this.next = next; } } ``` 2. 取出每個值 * 使用 ```!=null``` 取出每個值 * ```head=head.next;``` 表示跳至下一筆 * 忽略最後一個資料 ```head.next!=null``` ```csharp= while(head!=null){ Console.WriteLine(head.val); head=head.next; } ``` 3. 保留原始值 * 保留 * 建立新的 ListNode 儲存所有舊值 ```csharp= ListNode node=head; ``` * 控制 * 可使用原始名稱取值 ```csharp= int x=head.val; ``` * 輸出 * 輸出新 ListNode ```csharp= return node; ``` 4. 儲存值 * 使用 ```new``` 建立新 ```ListNode(值,下一個ListNode)``` ```csharp= head.next=new ListNode(值,head.next); ``` 5. 取值 * 當前值 * 使用 ```.val``` 取值 ```csharp= int x=head.val; ``` * 下一個值 * 使用 ```.next``` 表示下一個 ```csharp= int y=head.next.val; ``` ## 陣列 * 所有填入值 ```csharp= Array.Fill(arr, -1); ``` ## 二維陣列 1. 設定參數類型 ```csharp= int[][] arr ``` 2.取得列/欄數量 * 列 * 取得共幾列 ```csharp= arr.Length ``` * 欄 * 第 ```[i]```列的長度 ```csharp= arr[i].Length ``` 3. 取值 * 值:```陣列名稱[列index][欄index]``` ```csharp= row+=arr[i][j]; ``` ## 迴圈 * 跳過該圈 ```continue``` * while 迴圈 ```csharp= while(符合條件){ //執行 } ``` ## 進制轉換 * ```To類型```:ToInt表示```參數 String```轉```Int``` 1. 10進制轉2進制 ```ToString(數字,進制值)``` ```csharp= String b=Convert.ToString(10,2); ``` 2. 文字 ```ToInt32(文字,進制值)``` 轉10進制 * 使用16進制 ```csharp= long b=Convert.ToInt32(arr[i], 16); ``` * 使用2進制 * ```v=8``` ```csharp= int v = Convert.ToInt32(s, 2);//s=1000 ``` ## 類別轉換 1. char 轉 int ```csharp= char c='2'; int c_int=c-'0'; ``` ## Xor 互斥或 * 使用2進制 ```csharp= int a=5;//101 int b=3;//011 c=a^b;//110=6 ``` ## 格式化輸出 * ```變數名稱:"格式"``` * ```x4```->長度為4的16進制,```x8```->長度為8(前面補0) ```csharp= Console.WriteLine($"{h0:x8} {h1:x8}"); ``` * 小數點4位 * ```變數名稱.ToString("F位數")``` ```csharp= Console.WriteLine(y.ToString("F4")); ``` * ```1052```->```1052.0000``` * 小數點2位 ```0.00``` ```csharp= Console.WriteLine(sum.ToString("0.00")); ``` * 千分號 * 使用```ToString("#,#")``` ```csharp= Console.WriteLine(sum.ToString("#,#")); ``` ## Random 隨機產生數字 * 建立亂數物件 ```csharp= Random rnd = new Random(); ``` 1. 從0到x-1 ```Next(x)``` ```csharp= int r = rnd.Next(2); //0~1 ``` 3. 從x到y ```Next(x,y-1)``` ```csharp= int r = rnd.Next(1, 7);//1~6 ``` 4. 快速產生實心顏色 * 將RGB轉換為```Color```:```FromArgb(R值,G值,B值)``` ```csharp= Color ran_color() { int r = rd.Next(256); int g = rd.Next(256); int b = rd.Next(256); return Color.FromArgb(r, g, b); } ``` ## Class 建立 * 建立class ```csharp= public class data { public string name { get; set; } public int[] score { get; set; } public data(string name2, int[] score2) { name = name2; score = score2; } public double get_avg() { int sum = 0; for(int i=0; i<score.Length; i++) { sum += score[i]; } return sum/score.Length; } } ``` * 建立 Main方法 class ```csharp= class cls { static void Main() { int[] sor_list = { 50, 100, 80 }; data data_cls=new data("abc", sor_list); Console.WriteLine(data_cls.get_avg()); } } ``` ## ValueTuple * 功能類似於 ```class``` * 建立 ```csharp= List<(int year,int c)> list = new List<(int year,int c)>(); ``` * 新增值 ```csharp= list.Add((int.Parse(v[0]),c)); ``` * 印出值 ```csharp= list.ForEach(x => Console.WriteLine(x.c)); ``` ## 取得指定類型字元數量 * 格式 ```字串.Count(char.模式)``` * 大寫字母 ```csharp= int up_c_sum = pas.Count(char.IsUpper); ``` * 小寫字母 ```csharp= int low_c_sum = pas.Count(char.IsLower); ``` * 數字 ```csharp= int num_c = pas.Count(char.IsDigit); ``` * 符號 * ```IsWhiteSpace``` 檢查是否有空白 * ```IsLetterOrDigit``` 檢查是否為英文或數字 ```csharp= int sy_c = pas.Count(c => !char.IsLetterOrDigit(c) && !char.IsWhiteSpace(c)); ``` ## LINQ 查詢 * 格式:```list.指令``` * 選擇資料 ```Select``` * 取得最後一筆 ```Last``` * 尋找 ```Where(列=>列[欄位索引]==條件)``` * 移除重複 ```Distinct()``` * 跳過 ```Skip(筆數)``` * 取得前x筆 ```Take(筆數)``` * 取得平均值 ```Average()``` * 加總 ```Sum()``` ```csharp= List<int> list = new List<int>(); int c = list.Sum(); ``` * 排序 * 由小到大 ```csharp= OrderBy(列=>排序依據) ``` * 由大到小 ```csharp= OrderByDescending(列=>排序依據) ``` * 多層級排序 使用 ```ThenBy(row=>row[1])``` ```csharp= r_list = r_list.OrderBy(row => row[0]).ThenBy(row => row[1]).ToList(); ``` * 產生範圍數列 ```Range``` * 語法 ```csharp= Enumerable.Range(起始數字,數量); ``` * 產生 ```12345``` 的 ```String``` ```csharp= string s = string.Join("",Enumerable.Range(1,5)); ``` * 重複 ```Repeat``` ```csharp= var numbers = Enumerable.Repeat(0, n).ToList(); ``` ## Stack 堆疊 * 先進後出 * 建立 * ```Stack<類別>``` ```csharp= Stack<char> stk=new Stack<char>(); ``` * 新增 ```Push(內容)``` ```csharp= stk.Push(dict[row]); ``` * 取值 ```Pop()``` ```csharp= stk.Pop(); ``` * 取得頂端值 ```Peek()``` ```csharp= stk.Peek() ``` ## Queue 佇列 * 先進先出,與List差異是能夠取出(刪除) * 建立 ```csharp= Queue<int> qu = new Queue<int>(); ``` * 新增值 ```csharp= qu.Enqueue(x) ``` * 取值 ```csharp= int v=qu.Dequeue() ``` ## 檔案 * 文字檔案 * 取得文字 * ```ReadAllLines(檔名)``` 每列-回傳 ```String[]``` ```csharp= File.ReadAllLines(fn); ``` * ```ReadAllText(檔名)``` 取得所有文字-回傳 ```String``` ```csharp= File.ReadAllText(fn); ``` * 讀取中文 * 使用 Big5編碼 * ```讀取方法.(檔名,Encoding.GetEncoding("編碼方式"));``` ```csharp= File.ReadAllText("file.txt",Encoding.GetEncoding("Big5")); ``` * 圖片 * 開啟照片 ```FromFile(圖片名稱)``` * 有 ```using``` 結尾不用 ```;``` ```csharp= using(Image img=Image.FromFile(fn)) ``` * 若要省略 ```using``` (自動釋放資源)-> 手動釋放資源```Dispose()``` ```csharp= img.Dispose();//執行結尾加上 ``` * 儲存 * ```Save(路徑)``` 儲存照片 * ```Combine(資料夾名稱,檔案名稱)``` 組合路徑 ```csharp= img.Save(Path.Combine(dn, fn)); ``` * 資料夾 * 檢查是否存在 ```Exists(資料夾名稱)``` ```csharp= if (!Directory.Exists(dn)) ``` * 建立 ```CreateDirectory(資料夾名稱)``` ```csharp= Directory.CreateDirectory(dn); ``` * 檔案 * 檢查是否存在 ```Exists(檔名)``` ```csharp= if (File.Exists(fp)) ``` ## LinkedList 鍊結串列 * 建立 ```csharp= LinkedList<int> list = new LinkedList<int>(); ``` * 新增值 * 末端 ```csharp= list.AddLast(70); ``` * 前端 ```csharp= list.AddFirst(20); ``` * 刪除值 * 末端 ```csharp= list.RemoveLast(); ``` * 前端 ```csharp= list.RemoveFirst(); ``` * 取值 * 末端 ```csharp= list.Last.Value ``` * 前端 ```csharp= list.First.Value ``` ## List清單 * ```ForEach``` * 快速印出所有值 ```csharp= list.ForEach(e => Console.WriteLine(e)); ``` * 修改內容 * 使用 ```Select()``` 修改,再用 ```ToList()``` 儲存 ```csharp= x_list=x_list.Select(v=>Math.Max(1,v)).ToList(); ``` * 移除 ```csharp= List<string> arr = new List<string> { "A", "B", "C", "D", "E" }; ``` * 索引值 Index ```csharp= arr.RemoveAt(2);//移除C元素 ``` * 內容 ```csharp= arr.Remove("C")//移除C元素 ``` * 二維清單 ```List<List<int>>``` * 建立副本 * ```c_p List<int>``` 之後有改變不會影響 ```csharp= r_list.Add(new List<int>(c_p)); ``` ## Graphics 繪製 * 標準色彩筆刷 ```csharp= Pen pen = new Pen(Brushes.Black); ``` * 建立繪製物件 * Panel ```csharp= Graphics gs = panel1.CreateGraphics(); ``` * Image (照片檔案) * ```FromImage(照片)``` 表示繪製照片,照片為```Image```物件 ```csharp= Graphics gp = Graphics.FromImage(img) ``` * 繪製直線 * ```DrawLine(繪製物件,x起始值,y起始值,x結束值,y結束值)```:繪製線條 * ```Pen``` 物件:繪製顯條(不填滿) ```csharp= Pen pen = new Pen(Color.Black, 2); // 定義畫筆顏色和寬度 gs.DrawLine(pen, 10, 10, 100, 100); // 從 (10,10) 畫到 (100,100) ``` * 繪製圓點 * ```SolidBrush```:填滿 * ```DrawEllipse(繪製物件,x起始值,y起始值,x結束值,y結束值)```:繪製橢圓 ```csharp= SolidBrush sb = new SolidBrush(Color.Black); g.DrawEllipse(sb, 20, 70, 10, 10); // 在 (20,70) 畫一個 10*10 的橢圓 ``` * 繪製矩形框線 * ```DrawRectangle(繪製物件,x座標,y座標,高度,寬度)``` ```csharp= Pen bp = new Pen(Color.Black); gp.DrawRectangle(bp,10,10,10,50); ``` * 繪製文字 1. 建立字體 * ```new Font(字體名稱,大小,樣式)``` ```csharp= Font ft = new Font("Arial", 16, FontStyle.Bold); ``` 3. 建立筆刷 * ```csharp= Brush bh = Brushes.Black; ``` 5. 繪製文字 * ```DrawString(文字,字體,繪製物件,x座標,y座標)``` ```csharp= gp.DrawString("文字", ft,bh,v.x,v.y); ``` ## 函數 * 將函數作為參數 * 子函數為```Void``` * 建立函數 ```csharp= void ch_mode(Action fun){ fun();//執行函數 } ``` * 使用函數 * 函數名稱作為參數時,末端不須加上``()`` ```csharp= ch_mode(to_h); ``` ## Debug * 慢動作顯示 ```csharp= Thread.Sleep(1000); ``` ## Console * 背景顏色 ```BackgroundColor``` ```csharp= Console.BackgroundColor = ConsoleColor.Blue; ``` * 文字顏色 ```ForegroundColor``` ```csharp= Console.ForegroundColor = ConsoleColor.White; ``` * 還原顏色 ```ResetColor()```方法 ```csharp= Console.ResetColor(); ``` * 取得按鍵、等待暫停 ```ReadKey()``` * ```.key``` 表示取得按鍵名稱 * 小寫用```KeyChar```,大寫用```Key``` ```csharp= ConsoleKeyInfo keyInfo = Console.ReadKey(); ```