{%hackmd BJrTq20hE %} ###### tags: `C#` # C#入門 ## 第一行的Hello World Console.WriteLine()是把()內容以整行顯示在終端機中。 ``` Console.WriteLine("Hello World") //Hello World ``` 此外還有Console.Write(),與Console.WriteLine()不一樣的是他不會自動換行 ``` Console.Write("I'm Jay ") Console.Write("Hello World") //I'm Jay Hello World ``` ## 宣告變數 ### 字串的宣告 ``` string name = "Mark"; Console.WriteLine(name); ``` #### 組合字串 ``` string name = "Mark"; Console.WriteLine("Hello " + name); // Hello Mark ``` #### 字串插入 可以在$""中使用{}把變數插入,如以下範例 ``` string name = "Mark"; string greeting = "Hello"; Console.WriteLine($"{greeting} {name} !!"); // Hello Mark !! ``` 如果遇到字串有:與\要怎麼辦呢? 可以使用@ ``` string fileName = "Great-Porject" Console.WriteLine($@"c:\file\{fileName}\data"); //c:\file\Great-Porject\data ``` #### TrimStart、TrimEnd、Trim 以上的語法都是刪除自串的空白。 TrimStart 刪除字串左側所有的空白。 TrimEnd 刪除字串右側所有的空白。 Trim 刪除字串所有兩側的空白。 以下範例的[]是方便觀察。 ``` string name = " Mark "; Console.WriteLine($"[{name.TrimStart()}]"); //[Mark ] Console.WriteLine($"[{name.TrimEnd()}]"); //[ Mark] Console.WriteLine($"[{name.Trim()}]"); //[Mark] ``` #### Contains、IndexOf Contains的範例如下 ``` string name = "Chun-Chia"; Console.WriteLine(name.Contains("c")); //False 因為是小寫 Console.WriteLine(name.Contains("C")); // True ``` IndexOf的範例如下 ``` string name = "Chun-Chia"; Console.WriteLine(name.IndexOf("C")); // 0 只會回傳第一個找到C的位置 ``` ### 數字的宣告 在C#中基本的數字類別宣告有int、double、decimal #### int ``` int max = int.MaxValue; int min = int.MinValue; Console.WritLine(max); // 2147483647 Console.WritLine(min); // -2147483648 //但是 Console.WritLine(max +1); // -2147483648 max +1之後就會變最小值 Console.WritLine(min -1); // 2147483647 min -1之後就會變最大值 ``` #### 進行計算 ``` int a = 5; int b = 2; Console.WriteLine(a * b); //10 Console.WriteLine(a / b); //2 因為int只會顯示整數 ``` #### double double 可以允許小數點到14位 ``` double max = double.MaxValue; Console.WriteLine(max); //1.79769313486232E+308 double min = double.MinValue; Console.WriteLine(min); //-1.79769313486232E+308 ``` #### 進行計算 ``` double a = 10; double b = 3; Console.WriteLine(a / b); // 3.33333333333333 ``` #### decimal decimal 可以允許小數點到28位 ``` decimal max = decimal.MaxValue; Console.WriteLine(max); //79228162514264337593543950335 decimal min = decimal.MinValue; Console.WriteLine(min); //-79228162514264337593543950335 ``` 使用時在數字尾加上m或是M,如果沒加則當作double ``` decimal a = 10M; decimal b = 3M; Console.WriteLine(a / b); // 3.3333333333333333333333333333 ``` ## while 只要條件還是turn就會不斷執行 先判斷條件在執行 ``` int num = 0; while(num<5) { num ++; Console.WriteLine(num); } //1 //2 //3 //4 //5 ``` ## do while 先執行在判斷 ``` int num = 0; do{ num ++; Console.WriteLine(num); }while(num<5); ``` ### contunie continue間單的來說就是執行倒此停止,並執行下一輪的whie。 下面的範例8不會被顯示出來,表示num等於8時Console.WriteLine()被跳過去。 ``` int num = 0; while(num<10) { num ++; if(num == 8) continue; Console.WriteLine(num); } //1 //2 //3 //4 //5 //6 //7 //9 //10 ``` 英雄打怪獸的小程式 雙方HP10,攻擊力則是1-10亂數 由英雄先攻擊 ``` int heroHp = 10; int badHp = 10; Random damage = new Random(); while(heroHp > 0 && badHp > 0) { int numDanage = damage.Next(1,11); badHp -= numDanage; Console.WriteLine($"Hero attack Monster, caust {numDanage} damage. Monster now has {badHp} HP"); if (badHp <= 0) continue; numDanage = damage.Next(1,11); heroHp -= numDanage; Console.WriteLine($"Monster attack Hero , caust {numDanage} damage. Hero now has {heroHp} HP"); } Console.WriteLine(heroHp > badHp ? "Hero wins!":"Monster wins!"); ``` ## for 簡單的for回圈,顯示0-4 ``` for(int i = 0; i <5; i++) { Console.WriteLine(i); } //0 //1 //2 //3 //4 ``` 可以使用break跳出 原本i到10才會停止,因為多了if i ==7 的時候執行break,所以到7停止。 ``` for(int i = 0 ; i <= 10; i ++) { Console.WriteLine(i); if(i == 7) break; } //0 //1 //2 //3 //4 //5 //6 //7 ``` [for陳述式](https://learn.microsoft.com/zh-tw/training/modules/csharp-for/2-exercise-for) ## if elseif else 寫一個從0-5只累加被3整除的功能 ``` int counter = 0; for(int i = 0; i<10; i++) { if(i % 3 ==0) { counter = counter + i; } } Console.WriteLine(counter); ``` 寫一個判斷數值是否大於或等於10 int num = 10; if(num > 10){ Console.WriteLine($"The Number is {num} gratter than 10"); } else if(num == 10) { Console.WriteLine($"The Number is {num} equal 10"); } else{ Console.WriteLine($"The Number is {num} smaller than 10"); } ## List List起手式 宣告一個只有string的List ``` var names = new List<string> {"Chun-chia","Jay","May"}; ``` 宣告一個只有int的List ``` var names = new List<int> {0, 123, 888, 555}; ``` 提取List內的資料,依照資料順序第一個為0、第二個為1,需要寫在[]內,範例如下: ``` var names = new List<string> {"Chun-chia","Jay","May"}; Console.WriteLine($"The first data of List is {names[0].ToUpper()}") // CHUN-CHIA ``` ## foreach 可以對List使用,範例如下: ``` var names = new List<string> {"Jay","May","John","Kally"}; foreach(var name in names) { Console.WriteLine($"The List has {name}."); } //The List has Jay. //The List has May. //The List has John. //The List has Kally. ``` ### 編輯List內的資料 可以使用Add()增加資料、Reomve()移除資料 ``` var names = new List<string> {"Jay","May","John","Kally"}; names.Remove("May"); names.Add("Marry"); foreach(var name in names) { Console.WriteLine($"The List has {name}."); } //The List has Jay. //The List has John. //The List has Kally. //The List has Marry. ``` ### 計算List 內的資料數 Count ``` var names = new List<string> {"Jay","May","John","Kally"}; Console.WriteLine($"The List has {names.Count()} names"); // The List has 4 names ``` ### Select 不像JaveScript的forEach可以直接使用indx,在C#中如果需要使用index則需要再使用Select ``` var names = new List<string> {"Jay","May","John","Kally"}; foreach(var name in names.Select((value,index)=> new {value,index})) { Console.WriteLine($"The List index is {name.index} and the value is {name.value}"); } ``` ## IndexOf、Contains IndexOf可以尋找List中有沒有完全符合相同條件的資料並且回傳位置 例如 ``` var names = new List<string> {"Jay","May","John","Kally"}; var indexName = names.IndexOf("John"); Console.WriteLine(indexName); //2 代表John是第三個 ``` 如果List沒有資料則會回傳-1 ``` var names = new List<string> {"Jay","May","John","Kally"}; var indexName = names.IndexOf("Joy"); Console.WriteLine(indexName // -1 代表沒有找到 ``` Contains可以判斷List內是否有該資料 例如 ``` var names = new List<string> {"Jay","May","John","Kally"}; var isName = names.Contains("John"); Console.WriteLine(isName); //True ``` ## C#的隱性(implicitly)變數 什麼是隱性變數,簡單的來說就是給C#在執行編譯的時候,自動推斷該變數的型別。 以下的範例執行之後info的變數型別則會判斷為string ``` var info = "I'm string"; ``` 如果把info再另外附值為數字呢? ``` info = 50; // (2,8): error CS0029: Cannot implicitly convert type 'int' to 'string' ``` 會出現報錯 ## 使用var的時候需要完成變數的賦值 以下的範例沒有完成賦值,會出現報錯。 ``` var info; //(1,5): error CS0818: Implicitly-typed variables must be initialized //(1,5): error CS0168: The variable 'info' is declared but never used ``` ## 為什麼要用var 在C#中的宣告變數中可以知道所宣告變數的型別,但是在某些情況下的變數型別沒辦法一開始就知道,這個時候就可以使用var進行宣告。 ### Random 使用Random寫一個丟硬幣的程式 ``` Random coin = new Random(); // Random的數字是從1-2 int throwTheCoin = coin.Next(1, 3); Console.WriteLine(throwTheCoin); if(throwTheCoin == 1){ Console.WriteLine("HEAD"); } else{ Console.WriteLine("TAIL"); } ``` ## Value types 與 Reference type 學習到目前為止的的資料型別分類。實際上當然更多。 |Value types|Reference type| |-----|--------| |integral、floating |string、class、array| Value types can hold smaller values and are stored in the stack. Reference types can hold large values, and a new instance of a reference type is created using the new operator. Reference type variables hold a reference (the memory address) to the actual value stored in the heap. ## 字串轉數字 只有字串型別的數字才能轉成數字型別 ``` string myString = "123"; int myNum = int.Parse(myString); Console.WriteLine(myNum); // 123 ``` 只要將int.Parse()的int換成float、double、decimal等...就可以轉換成其他的數字型別。 例如: ``` string myString = "123.456789"; double myNum = double.Parse(myString); Console.WriteLine(myNum); //123.456789 ``` 那如果遇到不能轉換的資料呢?會報錯。 System.FormatException: Input string was not in a correct format. 這個時候就可以使用TryParse() TryParse()如果輸入的參數可以轉換成數字,那他本身就會return true,如果不能轉換則會return false。 要怎麼使用TryParse()呢? 數字型別.TryParse(要轉換的參數, out 數字型別的變數) 以下是範例: ``` string myString = "123.456789"; double myNum; if(double.TryParse(myString, out myNum)) { Console.WriteLine(myNum); } else { Console.WriteLine("The data can't convert to Number."); } ``` 另外還有Convert.ToInt32() ``` string value1 = "5"; int result = Convert.ToInt32(value1); Console.WriteLine(result); ``` 另外還有Convert.Decimal() ``` string value1 = "5"; decimal result = Convert.ToDecimal(value1); Console.WriteLine(result); ``` ## 數字轉為字串 使用ToString() ``` int num = 123; string myString = num.ToString(); string name = "Jack"; Console.WriteLine(name + myString); // Jack123 ``` ## 自動轉型為字串 只要數字遇到了字串 與 + 就會自動轉成字串 ``` int num = 123; string name = "Jack"; Console.WriteLine(name + num); // Jack123 ``` 那如果要數字相加之後再轉為字串呢? ``` int price1 = 55; int price2 = 20; string name = "Jack"; Console.WriteLine($"{name} spant {price1+price2} in buying things."); Console.WriteLine(name +"spant " +(price1+price2) + " in buying things."); //Jack spant 75 in buying things. ``` ## 數字間的型別轉換 以下範例是由decimal轉為float ``` decimal num = 1.123456789; float convertNum = (float)num; Console.WriteLine(convertNum); //1.123457 ``` 可以注意到轉為float時的小數點位數變小了,那是因為float的位數最多到6小數點位數。 這種轉換稱為narrowing conversion反過來則是widening conversion 其他的規則 範例如下 ``` int value = (int)1.5m; // casting truncates Console.WriteLine(value); //1 int value2 = Convert.ToInt32(1.5m); // converting rounds up Console.WriteLine(value2); //2 ``` :::info 一樣都是轉為int但是使用int會無條件捨去小數點,而Convert.ToInt32()會對小數點第一位四捨五入。 ::: ## 復合式字串格式 簡單的來說就是把變數當成參數傳入,字串內在放入{},並且依傳入參數的順序從左至右為0開始。 ``` string first = "Hello"; string second = "World"; Console.WriteLine("{1} {0}!", first, second); Console.WriteLine("{0} {0} {0}!", first, second); //World Hello! //Hello Hello Hello! ``` ## 設定貨幣格式 只要在數字型別的變數後面加上:C就會顯示貨幣符號,所顯示的貨幣符號與C#的文化設定有關,簡單的來說你的電腦設定在日本就會是日幣的符號。 文化特性代碼 位於美國的英文人士文化特性代碼為 en-US。 位於法國的法文人士文化特性代碼為 fr-FR。 位於加拿大的法文人士文化特性代碼為 fr-CA。 ``` decimal money = 10000m; int discount = 80; Console.WriteLine($"The total price is {money:C} and discount {discount:C}"); //The total price is ¤10,000.00 and discount ¤80.00 //The total price is NT$10,000.00 and discount NT$80.00 ``` ## 設定數字格式 在數字類別的變數後面加上:N,代表顯示至小數點第2位,第3位四捨五入。 ``` decimal num = 1.567M; Console.WriteLine($"{num:N}"); // 1.57 ``` 如果要小數第x位的話在:N加上數字就行,另外四捨五入的位數則是N+1 ``` decimal num = 1.567M; Console.WriteLine($"{num:N1}"); // 1.6 ``` ## 設定百分比格式 在數字類別的變數後面加上:P,代表顯示至小數點第2位,第3位四捨五入。 ``` decimal percent = 0.512786M; Console.WriteLine($"{percent:P}"); // 51.28 % ``` 如果要小數第x位的話在:P加上數字就行,另外四捨五入的位數則是P+1 ``` decimal percent = 0.512786M; Console.WriteLine($"{percent:P1"); // 51.3 % ``` ## 填補及對齊 會使用到PadRight()與PadLeft()語法。 以下的範例使用PadLeft(10)代表字串放到10個字元,10個字元扣掉變數的字元則放到左邊並以空白填補。 ``` string name = "Jack"; Console.WriteLine(name.PadLeft(10)); // Jack ``` 也可以使用其他符號,注意要使用單引號。 ``` string name = "Jack"; Console.WriteLine(name.PadLeft(10,'-')); //------Jack ``` ## 程式碼區塊會定義方法、類別和命名空間 [程式碼區塊會定義方法、類別和命名空間](https://learn.microsoft.com/zh-tw/training/modules/csharp-code-blocks/3-method-class-namespace) ## switch 只要所輸入的參數達成case條件就會執行,並以break通知程式執行完成並跳出switch。 ``` int employeeLevel = 200; string employeeName = "John Smith"; string title = ""; switch (employeeLevel) { case 100: title = "Junior Associate"; break; case 200: title = "Senior Associate"; break; case 300: title = "Manager"; break; case 400: title = "Senior Manager"; break; default: title = "Associate"; break; } Console.WriteLine($"{employeeName}, {title}"); // John Smith, Senior Associate ``` 其中的default則是如果都不符合case所設定的條件,就會執行 另外case可以多個條件,把條件寫在一起,範例如下 case 100:case 200: ``` int employeeLevel = 200; string employeeName = "John Smith"; string title = ""; switch (employeeLevel) { case 100: case 200: title = "Junior Associate"; break; case 300: title = "Manager"; break; case 400: title = "Senior Manager"; break; default: title = "Associate"; break; } Console.WriteLine($"{employeeName}, {title}"); // John Smith, Junior Associate ``` ## 陣列 是一種儲存資料的類別(class),提供許多方法處理資料。 陣列起手式 ``` string[] nameList = {"Jack","May","Havery","Kailly"}; int[] numList = {0, 45, 99}; ``` ### Array.Sort() 會把陣列資料中的第一個字元以ASCII code的規則從小大大排列 //待確定 ``` string[] pallets = { "B14", "A11", "B12", "A13" }; Array.Sort(pallets); foreach(var data in pallets) { Console.WriteLine(data); } //A11 //A13 //B12 //B14 ``` ### Array.Reverse() 把陣列的資料順續倒轉。 ``` string[] pallets = { "B14", "A11", "B12", "A13" }; Array.Reverse(pallets); foreach(var data in pallets) { Console.WriteLine(data); } //A13 //B12 //A11 //B14 ``` ### Array.Clear() 把資料移除的方法,但資料移除後為null,假設原本陣列長度為4,移除了0,1兩個資料之後,陣列長度仍然為4但是第一筆與第二筆資料會變為null,在Console.WriteLine()時,位隱性轉換為空字串。 使用方法Array.Clear(代處理資料的陣列,從第幾個資料開始,要移除幾個資料) ``` string[] pallets = { "B14", "A11", "B12", "A13" }; Array.Clear(pallets,0,2) foreach(var data in pallets) { Console.WriteLine(data); } // // //B12 //A13 ``` ### Array.Resize() 改變陣列長度的方法,如果是從長度6改成長度3那第3-5筆資料則會消失。 使用方法Array.Resize(ref 待處理陣列, 要改成多長) ``` string[] pallets = { "B14", "A11", "B12", "A13", "C57" ,"C91" }; Array.Resize(ref pallets, 3) foreach(var data in pallets); { Console.WriteLine(data); } //B14 //A11 //B12 ``` ### Split() 是一個可以依照條件分割資料並行成陣列的方法。 使用方法 待處理陣列.Split('分割條件')//注意要用'' ``` string pangram = "The quick brown fox jumps over the lazy dog"; string[] splitArr = pangram.Split(' '); foreach(var data in splitArr) { Console.WriteLine(data); } //The //quick //brown //fox //jumps //over //the //lazy //dog ``` ### String.Join() 把陣列加入字串或是符號並形成字串的方法 使用方法 String.Join("字串",陣列) ``` string pangram = "The quick brown fox jumps over the lazy dog"; string[] splitArr = pangram.Split(' '); string result = Strimg.Join(",", splitArr); Console.WriteLine(result); // The,quick,brown,fox,jumps,over,the,lazy,dog ``` ### ToCharArray() 把字串轉為陣列的方法 ``` string myString = "I'm string."; char[] myStrimgArray = myString.ToCharArray(); foreach(var latter in myStrimgArray) { Console.WriteLine(latter); } //I //' //m // //s //t //r //i //n //g //. ``` ### string挑戰 把The quick brown fox jumps over the lazy dog輸出為ehT kciuq nworb xof spmuj revo eht yzal god ``` string pangram = "The quick brown fox jumps over the lazy dog"; string[] splitArr = pangram.Split(' '); foreach(var data in splitArr.Select((value,index)=>new {value,index})) { char[] arrayWorld = data.value.ToCharArray(); Array.Reverse(arrayWorld); // foreach(var i in arrayWorld) // Console.WriteLine(i); splitArr[data.index] =new string(arrayWorld); } string result = String.Join(" ",splitArr); Console.WriteLine(result); //ehT kciuq nworb xof spmuj revo eht yzal god ``` ### string挑戰2 挑出B開頭的資料,並且只顯示B開頭的資料 "B123,C234,A345,C15,B177,G3003,C235,B179" ``` string orderStream = "B123,C234,A345,C15,B177,G3003,C235,B179"; string[] orderArray = orderStream.Split(','); foreach(var order in orderArray) { if(order.StartsWith("B")) Console.WriteLine(order); } //B123 //B177 //B179 ``` ## 使用字串方法處理資料 ### IndexOf() 會顯示由左到右第一個符合條件的位置。 如何使用 字串.IndexOf("條件"); ``` string name = "John"; int result = name.IndexOf("h"); Console.WriteLine(result); //2 ``` [IndexOf範例](https://learn.microsoft.com/zh-tw/training/modules/csharp-modify-content/2-exercise-indexof-substring) ### Substring() 擷取某一段字串的片段。 如何使用 字串.Substring(從第幾個字元開始,要擷取多少字元) ``` string myString = "0123456789"; string result = myString.Substring(3,4); Console.WriteLine(result); //3456 ``` ### Remove() 移除某一段字串的片段。 如何使用 字串.Remove(從第幾個字元開始,要移除多少字元) ``` string myString = "0123456789"; string result = myString.Remove(3,4); Console.WriteLine(result); //012789 ``` ### Replace() 替換符合條件的字串,也可以用來移除。 使用方法 字串.Replace("被替換的字串","要替換的字串") ``` string message = "This--is--ex-amp-le--da-ta"; message = message.Replace("--", " "); message = message.Replace("-", ""); Console.WriteLine(message); //This is example data ``` ### 字串挑戰 把\<div>\<h2>Widgets ™\</h2>\<span>5000\</span><\/div> 輸出為\<h2>Widgets ®\</h2>\<span>5000\</span> 並且取出\<span>5000\</span>的5000 ``` const string input = "<div><h2>Widgets ™</h2><span>5000</span></div>"; string quantity = ""; string output = ""; const string openSign = "<span>"; const string endSign = "</span>"; int quantityStart = input.IndexOf(openSign); int quantityEnd = input.IndexOf(endSign); int openSignLen = openSign.Length; quantityStart += openSignLen; quantity = input.Substring(quantityStart, (quantityEnd - quantityStart)); const string openSign2 = "<div>"; const string endSign2 = "</div>"; int quantityStart2 = input.IndexOf(openSign2); int openSign2Leng = openSign2.Length; output = input.Remove(quantityStart2,openSign2Leng); int quantityEnd2 = output.IndexOf(endSign2); int endSign2Leng = endSign2.Length; output = output.Remove(quantityEnd2,endSign2Leng); output = output.Replace("trade","reg"); Console.WriteLine(quantity); Console.WriteLine(output); //5000 //<h2>Widgets ®</h2><span>5000</span> ```
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.