[C#学习笔记8]string详解、null问题解决、stringBuilder高效处理
注意:下标从0起始
示例1:IndexOf方法的使用,字符的位置
string email = "xiaoqiang@qq.com";
int position = email.IndexOf("@");//9
int position1 = email.IndexOf("qq.com");//10
int position2 = email.IndexOf("qq.com1");//-1
int position3 = email.LastIndexOf("q");//11
int lenght = email.Length;//获取字符串的长度
Console.WriteLine("@所在位置索引:" + position);
示例2:Substring方法的使用,子字符串
string email = "xiaoqiang@qq.com";
string userName = email.Substring(0, 9);//xiaoqiang 起始位置0取9个字符
string userName1 = email.Substring(0, email.IndexOf("@"));//取@字符所在位置之前
string userName2 = email.Substring(9);//@qq.com 从第9个字节
Console.WriteLine("邮箱用户名:" + userName);
示例3:比较字符串是否相等
string name1 = "xiaowang";
string name2 = "xiaowang";
string name3 = "wang";
Console.WriteLine(name1 == name2);//True
Console.WriteLine(name1.Equals(name2));//True
Console.WriteLine(name2 == name3);//False
Console.WriteLine(name2.Equals(name3));//False
示例4:获取字符串的长度
string userPwd = "88996677ABE";
int pwdLength = userPwd.Length;//
Console.WriteLine("密码长度:{0}", pwdLength);
示例5:字符串格式化
string name = "小王";
int age = 20;
Console.WriteLine("我的姓名:{0} 年龄:{1}", name, age);//我的姓名:小王 年龄:20
Console.WriteLine($"我的姓名:{name} 年龄:{age}");//我的姓名:小王 年龄:20
string newString = string.Format("我的姓名:{0} 年龄:{1}", name, age);//我的姓名:小王 年龄:20
string newString1 = $"我的姓名:{name} 年龄:{age}";//我的姓名:小王 年龄:20
Console.WriteLine(newString);

字符串空值:string name1 = string.Empty;
示例7:字符串其他方法
Console.WriteLine(" xiao ".Trim() == "xiao");//去掉前后多余空格
Console.WriteLine("xiao".ToUpper());//转换成大写 ToLower转小写
string url = "http://www.xiletu.com/DetailPer.aspx?JianLiId=86";
Console.WriteLine("最后一个点的位置:{0}", url.LastIndexOf("."));//找到最后一个匹配项位置
示例8:字符串的高效处理
string strText = "我正在学习";
strText += ".NET平台";//浪费内存空间
strText += "与C#开发语言";
Console.WriteLine(strText);

StringBuilder builder = new StringBuilder("我正在学习");
builder.Append(".NET平台");
builder.Append("与C#开发语言");
string info = builder.ToString();
Console.WriteLine(info);


