標籤:style blog http ar io color 使用 sp for
///C#字串是使用string關鍵字聲明的一個字元數組,它也是一個對象,封裝了所有字串操作,如比較、插入、刪除、尋找等。
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { //建立一個字串 string str1 = "apple orange banana"; Console.WriteLine("str1:+str1"); ///建立另一個字串 string str2 = str1 + "peach"; Console.WriteLine("str2:" + str2); //比較兩個字串是否一致 if (String.Compare(str1, str2) == 0) { Console.WriteLine("str1 和str2兩個字串一致"); } else { Console.WriteLine("str1和str2兩個字串不一致"); } //從第0個位元組開始尋找空格的位置 int n=str1.IndexOf(‘ ‘,0); Console.WriteLine("str1第一個空格在第{0}個位元組",n); ///刪除第1個空格之後的所有字元 str2=str1.Remove(n); Console.WriteLine("刪除str1第一個空格後的所有字元:"+str2); ///將所有空格替換為- str2=str2.Replace(‘ ‘,‘-‘); Console.WriteLine("將所有的空格替換為-:"+str2); ///在第一個空格之後插入@@@ str2=str1.Insert(n,"peach"); Console.WriteLine("在str1第一個空格插入peach:"+str2); ///取第一個空格後的6個字元 str2=str1.Substring(n+1,6); Console.WriteLine("取str1第一個空格後的6個字元:"+str2); ///以空格為標記,將字串分解為若干個新的字串 char[]chars={‘ ‘}; string[]strs=str1.Split(chars); Console.WriteLine("以空格為標識符,將str1分解為:"); for(int i=0;i<strs.Length;i++) Console.WriteLine(i+":"+strs[i]); ///按任意鍵退出 Console.ReadKey(); } }}
C#字串