c#(字串方法總結)

來源:互聯網
上載者:User

標籤:出現   截取   空格   c#   去除   format   作用   一個   比較   

1.字元數組與字串的轉換

(1)ToCharArray()將字串轉換成字元數組

     string s=‘我喜歡部落格’;

     char[] chs=s.ToCharArray();

(2)將字元數組new string()得到字串

     s=new string(chs);

2.判斷字串是否為空白:IsNullOrEmpty(),傳回值為bool類型

   string s=null:

   if(string.isNullOrEmpty(s))

   {

     Console.WriteLine("字串為空白");

   }

  else

  {

    Console.WriteLine("字串不為空白");

  }

3.字串比較是否相等:equal(),其中比較的是地址(這句話某些地方不是很理解),StringComparison.OrdinalIgnoreCase表示忽略大小寫

  string s1="abcd";

  string s2="ABCD";

  if(s1.Equal(s2,StringComparison.OrdinalIgnoreCase))

  {

   Console.WriteLine("相同");

  }

  else

  {

  Console.WriteLine("不同");

  }

4.尋找字串中某個字元的位置

(1)IndexOf():尋找某個字元在字串中出現的首位置

         string s="我喜歡部落格";

         int index=s.IndexOf(‘喜‘);//結果是index=1

(2)LastIndexOf()

         string s="我喜歡部落格,喜歡這裡";

         int index=s.LastIndexOf(‘喜‘);//結果是index=6

(3)兩個方法都可在字元參數後再跟一個整形參數,表示從第幾個開始尋找

         string s="我喜歡部落格";

         int index=s.IndexOf(‘喜‘,1);//從第一個開始尋找,包括第一個

5.字串截取函數Substring()

  string s="abcdefg";

  s=s.Substring(1,4);//表示從第一個開始截取,截取到第四個但不包括第四個;第二個參數可不要,表示截取到最末尾

6.split()

   string s = "a , -- b";

  string[] newS = s.Split(new char[] { ‘ ‘, ‘-‘, ‘,‘ }, StringSplitOptions.RemoveEmptyEntries);//new char[] { 要去除的s字串中的字元},StringSplitOptions.RemoveEmptyEntries參數的                                                                                                                                              作用是去掉得到的新字串數組中的空格

  newS[0]="a";

  newS[1]="b";

7.字串插入函數Join()

  string[] names = { "張三", "李四", "王五", "趙六" };

  string s1 = string.Join("|",names);//s1="張三|李四|王五|趙六|"

  string s2 = string.Join("|",1,3.14,true,‘c‘,5000m,"張三");//s2="1|3.14|true|c|5000|張三|"

8.字串格式化函數Format()

  string s=string.Format("我今年{0}歲}",20);//s="我今年20歲"

 

註:此文章為本人學習總結所用,若有侵權行為,請聯絡我qq:2216297280,我會儘快刪除。同時也歡迎各位學友前來評論,謝謝!

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.