C# 字串

來源:互聯網
上載者:User

從今天開始記錄c#之路

C#學習  字串

      C#的字串是參考型別,不可變性和密封性是字串類型的兩個類型,字串一旦建立就不能修改了,所有看上修改了的字串只是建立了一個新的字串並返回一個對新字串的引用。

      字串類型不能被繼承

  • 格式化字串
string str = "my name is {0},I like {1},My age is{2}";
Console.WriteLine(string.Format(str,"minlecun","tudou","26"));
  • 連接字串
string str1 = "hello";
string str2 = " ";
string str3 = "world";
Console.WriteLine(string.Concat(str1, str2, str3));
  • 遍曆字串

     可以像數組一樣遍曆字串
     string theString = "hello,world";
     char theFristChar = theStringp[0];
     字元是唯讀,不能對單個字元進行修改
     string theString = "hello,world";
     theString[0] = 's';//wrong

  • 與數組類似,可以用Length獲得字串長度
  • 可以用foreach對字串進行遍曆
     string theString = "hi,world";
foreach(char s in theString)
{
Console.Write(s);
}
  • 可以通過ToCharArray()形式來獲得表示字串的字元數組
   string theString = "hello World";
char[] theChars = theString.ToCharArray();
  • Trim去2頭的空格,TrimStart去開頭的指定字串,TrimEnd去結尾的指定字串
   string s = "aaasssddd";
string s1 = "asasasddd";
Console.WriteLine(s.TrimStart(new char[] {'a','s'})); //ddd.
Console.WriteLine(s1.TrimStart(new char[] {'a','s'})); //sasasddd.
  • PadLeft或PadRight 添加開頭和結尾的指定的字元
   string s = "12345";
Console.WriteLine(s.PadLeft(10,'v')); //vvvvv12345
string s = "12345";
Console.WriteLine(s.PadLeft(5,'v')); //12345
string s = "12345";
Console.WriteLine(s.PadLeft(3,'v')); //12345
  • split 將字串按指定的字元分割成字串片段,得到的是字串數組
            string str = "one two_three=four";
string[] arr = str.Split(new char[] {' ','_','='});
foreach (string s in arr) {
Console.WriteLine(s);
}
  • substring 可以擷取指定位置到結束的字串片段 第一個參數是起始位置 第2個是截取字串的長度
            string str="0123456789";
string newStr = str.Substring(3);
Console.WriteLine(newStr);
string newStr2 = str.Substring(3,1);
Console.WriteLine(newStr2);

 

  • repalce 替換字串指定的字串
            string str = "asdasdzxc";
Console.WriteLine(str.Replace('a', '1'));

 

  • remove 刪除字串中指定位置的字串片段 第一參數是位置 第2個參數是長度
            string str = "0123456789";
Console.WriteLine(str.Remove(5));
Console.WriteLine(str.Remove(5,1));

 

  • indexOf 尋找指定的字串在字串中得位置,第一個參數是要尋找的字串 第2個參數起始位置
            string str = "ok is ok";
Console.WriteLine(str.IndexOf("ok"));
Console.WriteLine(str.IndexOf("ok",1));

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.