從今天開始記錄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);
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));