//字符串訪問 //string s = "ABCD"; //Console.WriteLine(s[0]);//第0位字符 //Console.WriteLine(s.Length);//字符串長度 //----------------------------------------------------------- //打散 //string s = "ABCD"; //char[] arr = s.ToCharArray();//將字符串打散,並放入字符數組中. //Console.WriteLine(arr[0]);//arr[0]='A',arr[1]='B',arr[2]='C',arr[3]='D' //----------------------------------------------------------- //截取 //string s = "ABCD"; //Console.WriteLine(s.Substring(1));//從第二位開始截取到最後一位,顯示BCD //Console.WriteLine(s.Substring(2, 2));//從第三位開始截取二個,顯示CD //----------------------------------------------------------- //字符匹配 //string s = "ABCABCD"; //Console.WriteLine(s.IndexOf('A'));//找到該字符,返回所在位置.輸出0 //Console.WriteLine(s.IndexOf("BCD"));//找到該串,返回頭所在位置.輸出4 //Console.WriteLine(s.IndexOf('E'));//當找不到任何相關的匹配時,輸出-1; //Console.WriteLine(s.LastIndexOf('C'));//從末尾開始匹配,輸出5 //Console.WriteLine(s.LastIndexOf("AB"));//同上,輸出3 //Console.WriteLine(s.Contains("ABCD"));//判斷此字符串是否是在另外一字符串匹配 //----------------------------------------------------------- //大小寫轉換 //string s = "aBcD"; //Console.WriteLine(s.ToLower());//將字符串轉爲小寫,輸出abcd //Console.WriteLine(s.ToUpper());//將字符串將爲大小,輸出ABCD //----------------------------------------------------------- //匹配移除 //string s = "_@$_AB__CD_$@_"; //Console.WriteLine(s.Trim('_'));//移除首和尾匹配字符,輸出@$_AB__CD_$@ //Console.WriteLine(s.TrimStart('_'));//移除首部字符,輸出@$_AB__CD_$@_ //Console.WriteLine(s.TrimEnd('_'));//移除尾部字符,輸出_@$_AB__CD_$@ //Console.WriteLine(s.Trim('_', '@', '$'));//只能移除字符,能夠寫不少..輸出AB__CD //----------------------------------------------------------- //插入和刪除 //string s = "ADEF"; //Console.WriteLine(s.Insert(1, "BC"));//在字符串什麼位置插入字符串,輸出ABCDEF //Console.WriteLine(s.Remove(1));//從字符串第二個位開始到最後的字符都刪除,輸出A //Console.WriteLine(s.Remove(0, 2));//從第一位開始刪除二個字符,輸出EF //----------------------------------------------------------- //替換 //string s = "A_B_C_D"; //Console.WriteLine(s.Replace('_', ':'));輸出A:B:C:D //Console.WriteLine(s.Replace("_", ""));//只有字符串才能替換空字符,輸出ABCD //----------------------------------------------------------- //分割 //string s = "A,B,C,D"; //string[] arr = s.Split(','); //Console.WriteLine(arr[0]);輸出A //Console.WriteLine(arr[1]);輸出B //Console.WriteLine(arr[2]);輸出C //Console.WriteLine(arr[3]);輸出D //----------------------------------------------------------- //鏈接 //string[] arr = new string[] { "A", "B", "C", "D" }; //Console.WriteLine(string.Concat(arr));//鏈接字符串數組 //Console.WriteLine(string.Join(",", arr));//鏈接字符串數組,並帶有分隔 //StringBuilder stringBuilder = new StringBuilder();//一種很高效的鏈接字符串的方式 //stringBuilder.Append(arr[0]); //stringBuilder.Append(arr[1]); //stringBuilder.Append(arr[2]); //stringBuilder.Append(arr[3]); //Console.WriteLine(stringBuilder.ToString());
|