整理下操作字符串相關(guān)的屬性和方法,主要是string和stringbuilder的使用。
字符串中可以包含轉(zhuǎn)義符,如“\n”(新行)和“\t”(制表符)。
如果希望包含反斜杠,則它前面必須還有另一個反斜杠,如“\\”。
@ 符號會告知字符串構(gòu)造函數(shù)忽略轉(zhuǎn)義符和分行符。
string str = "-hello,world-";
一般用Trim來刪除指定字符,或者去除空格
Console.WriteLine(str.Trim('-'));//hello,world
Console.WriteLine(str.TrimEnd('-'));//-hello,world
Console.WriteLine(str.TrimStart('-'));//hello,world-
字符串訪問,直接用索引即可,得到對應(yīng)的字符
Console.WriteLine(str[1]);//輸入h
字符串遍歷成單字節(jié)
foreach (char myChar in str)
{
Console.WriteLine("{0}", myChar);
}
輸出.png
字符串轉(zhuǎn)字節(jié)數(shù)組ToCharArray
char[] c = str.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
Console.WriteLine(c[i]);
}
輸出效果和遍歷成單字節(jié)一樣
分割字符串Split
string[] s = str.Split(',');
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine(s[i]);//s[0]=-hello s[1]=world
}
多個不同的字符也可分割,例如
string s1 = "hello-world*hello curry";
string[] s2 = s1.Split('-', '*', ' ');
for (int i = 0; i < s2.Length; i++)
{
Console.WriteLine(s2[i]);
}
此時輸出為
分割字符串.png
串聯(lián)字符串
Console.WriteLine(string.Join("*",new object[]{12,"hello",DateTime.Now}));
Console.WriteLine(string.Join(" ",12,"hello",36));
替換字符串
Console.WriteLine(str.Replace('-', '*'));//*hello,world*
獲取指定字符對應(yīng)的索引位置
Console.WriteLine(str.IndexOf(','));//6
Console.WriteLine(str.IndexOf('。'));//-1 如果找到該字符,則為 value 的從零開始的索引位置;如果未找到,則為 -1。
Console.WriteLine(str.LastIndexOf('-'));//12
Console.WriteLine(str.Contains('-'));//true
截取字符串
Console.WriteLine(str.Substring(1));//hello,world-,從位置1開始到最后的全部截取出來
Console.WriteLine(str.Substring(1, 5));//hello,第一個為開始位置,第二個為長度
移除字符串
Console.WriteLine(str.Remove(1));//輸出-,從位置1開始到最后的全部刪除
Console.WriteLine(str.Remove(0, 6));//輸出,world-
//第一個為開始位置,第二個為長度
字符串開頭與指定的字符串匹配
Console.WriteLine(str.StartsWith("hello"));//false
Console.WriteLine(str.StartsWith("-HELLO", true, null));//true 忽略大小寫,使用當(dāng)前區(qū)域
字符串的大小寫轉(zhuǎn)換ToLower轉(zhuǎn)小寫,ToUpper轉(zhuǎn)大寫
Console.WriteLine(str.ToLower());
Console.WriteLine(str.ToUpper());//-HELLO,WORLD-
使字符串達到指定長度實現(xiàn)對齊
Console.WriteLine(str.PadLeft(15,'-'));//在字符左側(cè)填充字符來達到指定的總長度,從而實現(xiàn)右對齊
Console.WriteLine(str.PadRight(15, '-'));//在字符右側(cè)填充字符來達到指定的總長度,從而實現(xiàn)左對齊
stringbuilder的使用方法
首先new一個新的StringBuilder
StringBuilder sb = new StringBuilder("Hello World!");
輸出長度
Console.WriteLine(sb.Length);//12
sb.Capacity = 10;
設(shè)置最大長度為10
sb.EnsureCapacity(10);
設(shè)置要確保的最小容量
//向StringBuilder增加新元素
Console.WriteLine(sb.Append("123"));
StringBuilder sb1 = new StringBuilder("Hello World!");
Console.WriteLine(sb1.AppendFormat("第一個{0},第二個{1}","Beijing",2008));//注意第一個是從0開始
//向指定的索引位置插入字符串
Console.WriteLine(sb.Insert(6,"beautiful "));
//從指定的索引位置移除指定長度的字符
Console.WriteLine(sb.Remove(5,10));
//替換字符
Console.WriteLine(sb.Replace("!","*"));
//將StringBuilder轉(zhuǎn)為String類型
Console.WriteLine(sb.ToString());
輸出結(jié)果為
stringbuilder.png