標籤:style blog http ar color os sp for strong
String類
概念:是一個class類型的類,裡麵包含許多處理字串的方法和屬性
1、length方法。 例:
string s = "hello";Console.WriteLine("s的長度為{0}",s.Length);//擷取字串長度,返回int值
2、Trim & ToUpper方法。例:
string i = " hello ";Console.WriteLine("i的值為:{0}",i+"a");Console.WriteLine("i去除空格後的值為:{0}",i.Trim()+"a");Console.WriteLine("i去除左邊空格後的值為:{0}",i.TrimStart()+"a");Console.WriteLine("i去除右邊空格後的值為:{0}",i.TrimEnd()+"a");Console.WriteLine("i大寫形式為:{0}", i.ToUpper());
3、indexof :從0開始的索引。例:
string ss = "abcdefc";Console.WriteLine(ss.IndexOf("c"));//ctrl+shift+空格 第一個匹配項的首字母索引Console.WriteLine(ss.LastIndexOf("c"));//最後一個匹配項的首字母索引
4、startswith endswith:判斷是否以某個字串開頭/結尾,返回布爾值。例:
bool b1 = ss.StartsWith("ab");bool b2 = ss.EndsWith("fc");Console.WriteLine(b1+","+b2);
5、contains:判斷字串中是否包含某個字元段,返回布爾值。例:
Console.WriteLine(ss.Contains("bc"));
6、substring:截取字串。例:
Console.WriteLine("從第2個索引開始的3個字元為{0}",ss.Substring(2, 3));//從指定索引“2”開始列印長度“3”個字元Console.WriteLine("從第二個索引開始一直到最後的字串為{0}", ss.Substring(2));//從指定索引“2”截取到最後
7、tostring:轉換成字串。例:
DateTime date = DateTime.Now;string sss = date.ToString("yyyy年MM月dd日hh時mm分ss秒");Console.WriteLine(sss);double dd = 1.234;string sss1 = dd.ToString("#.00");//小數點後有幾個#取幾位元,小數點前的#取所有位元,如果小數點後面是0,用“.00”的時候補零(如果不是0會顯示原數),“.##”不會補零Console.WriteLine(sss1);Math類
是指數學運算的各種方法,大家可以嘗試輸入Math.查看它的方法,此處我唯寫一個:
Math.Floor/Celing:地板值(最小值)、天花板值(最大值)。例:
Console.WriteLine("3.14的地板值為{0}",Math.Floor(3.14));//3.00Console.WriteLine("3.14的天花板值為{0}",Math.Ceiling(3.14));//4.00Datetime類
1、now: 擷取系統目前時間
DateTime dt = DateTime.Now;dt = dt.AddYears(3);//在目前時間下加三年(同時也可以寫AddMonths,AddDays,AddHours,等)
Console.WriteLine(dt);//輸出結果比目前時間多加了三年
2、與TimeSpan的合用:
DateTime da = new DateTime(1990, 01, 01);TimeSpan t = new TimeSpan(2,10,20,0) ;//TimeSpan(days,hours,minutes,seconds)da = da.Add(t);Console.WriteLine(da);
Console.Clear();//清空控制台上的所有資訊
練習
1、輸入一個社會安全號碼,截取生日
Console.WriteLine("請輸入社會安全號碼:");string id = Console.ReadLine();if (id.Length == 18){ Console.WriteLine("生日為:{0}年{1}月{2}日",id.Substring(6,4),id.Substring(10,2),id.Substring(12,2));}else Console.WriteLine("您的輸入有誤");查看答案
2、隨機產生四位驗證碼(0~9,a~Z)
Random r = new Random();string yan = "0123456789abcdefghjklmnopqistuvwxyzABCDEFGHIJKLMNOPQISTUVWXYZ";string yzm = "";for (int j = 0; j < 4; j++){ int ra = r.Next(yan.Length); yzm = yan.Substring(ra, 1)+yzm;}Console.WriteLine(yzm);查看答案
7、C#基礎整理(類)