字符串的处理
字符串的常见操作
1.取字符串的长度
1 string str = "Spiderman"; 2 int Len = str.Length; //得到字符串str的长度
2.截取字符串
重载一:string string.Substring(int startIndex);
1 string str = "Spiderman"; 2 Console.WriteLine(str.Substring(6)); //输出man
重载二:string string.Substring(int startIndex, int length);
1 string str = "china"; 2 Console.WriteLine(str.Substring(6,3)); //输出man
3.字符串相加
方法一:
1 string str = "S" + "pider" + "man"; //输出Spiderman
方法二:
1 StringBuilder sb = new StringBuilder(); 2 sb.Append("S"); 3 sb.Append("pider"); 4 sb.Append("man"); //输出Spiderman
StringBuilder方法与"+"方法效果一样,但StringBuilder性能更好。
4.清除字符串前后包含的空格
1 string str = " Spiderman "; 2 Console.WriteLine(str.trim()); //输出Spiderman
5.替换字符串
1 string str = "Spiderman"; 2 string str1 = str.Replace("Spider", "Super"); 3 Console.WriteLine(str1); //输出Superman