C#字串操作(一)

來源:互聯網
上載者:User

標籤:

C#內建類型中,字串是唯一的參考型別,具有不可變性和密封性。

不可變性指字串一旦建立成功,將不可更改,str1=str1,實際上在堆新建立了一個str1字串對象,並且返回對該對象的引用。

密封性指字串不能被繼承。

不可變性和密封效能保證字串類型更加高效和安全。

字串操作

1、格式化字串

String.Format

  string str1 = "puguo  2530";  string strFormat = "{0,20}";//字串格式化佔20字元  string strResult=string.Format(strFormat,str1);  Console.WriteLine("string.Format({0},{1})=[{2}]\n",strFormat,str1,strResult);
標準數字格式化字串 含義 執行個體
C或c 貨幣 string.Format("{0:C}",10)=¥10.00
D或d 補位 string.Format("{0:D3},10")=010
E或e 指數 string.Format("{0:E3},10")=1.000e+001
F或f 固定點 string.Format("{0:F3},10")=10.000
G或g 常規 string.Format("{0:G3},10")=10
N或n 千分符 string.Format("{0:N},10000")=10,000.00
P或p 百分比符號 string.Format("{0:P},1")=100%
X或x 十六制 string.Format("{0:X}",1900)=96C

 

自訂數字格式化字串 含義
0 0預留位置
# 數字預留位置
. 小數點
千位分隔字元
段分割符
% 百分符

 

2、比較字串

(1)、string.Compare(str1,str2)

    str1<str2   --->-1

    str1==str2 --->0

    str1>str2   --->1

(2)、string.CompareOrdinal(str1,str2); 與(1)區別,與本地化無關

    str1<str2   --->-1

    str1==str2 --->0

    str1>str2   --->1

(3)、str1.CompareTo(str2);

    str1<str2   --->-1

    str1==str2 --->0

    str1>str2   --->1

    str2 is null  --->1    ""比null大

(4)、string.Equals(str1, str2)  <==> str1==str2

    str1==str2 --->0

    str1!=str2 --->!0

(5)、 str1.Equals(str2) 

    str1==str2 --->0

    str1!=str2 --->!0

(6)、str1==str2

總結:靜態方法比執行個體方法效率高,因為靜態方法比執行個體方法先載入。總的來說,(1)(2)比(3)好,(4)比(5)好

3、字串串連

    (1)、str1+str2

    (2)、string.Concat(str1,str2)

4、複製字串

   (1)、str2=string.Copy(str1); 

         copy建立一個新的執行個體字串對象,str2,str1不是指向同一字串引用。

   (2)、str2=str1

         直接複製,str2與str1指向同一字串引用。字串的不可變性導致字串引用的指不可變,改變字串的指知識改變字串指向的字串引用。

   (3)、str2=(string)str1.clone()

         str1.clone()返回的是object類型,強制轉化為string,與(2)效果一致。

 

C#字串操作(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.