字符串的声明和初始
string str1 = "we are student";
string str2= "we are student";
Console.WriteLine(str1);
Console.WriteLine(str2);
Console.ReadKey();
提取字符串信息
获取字符串长度
string str1 = "123 456";
int size = str1.Length;
Console.WriteLine(size);
Console.ReadKey();
获取指定位置字符
string str1 = "123 456";
char str = str1[5];
Console.WriteLine("索引为5的为{0}",str);
Console.ReadKey();
获取子字符串索引
string str1 = "123 456";
int size=str1.IndexOf('4');
Console.WriteLine("4的索引为{0}",size);
Console.ReadKey();
//
//最后一次搜索值得索引
string str1 = "123 4564";
int size=str1.LastIndexOf('4');
Console.WriteLine("最后一个4的索引为{0}",size);
Console.ReadKey();
判断字符串首尾内容
//首尾内容判断
string _name = "世界上最好的语言c#";
bool flag=_name.StartsWith("世界");
bool flag2 = _name.EndsWith("c#");
Console.WriteLine(flag);
Console.WriteLine(flag2);
Console.ReadKey();
字符串操作
拼接字符串
//拼接字符串
string str1 = "123";
string str2 = "456";
string s=str1+""+str2;
Console.WriteLine(s);
Console.ReadKey();
比较字符串
//比较字符串
Console.WriteLine("输入用户名");
string name=Console.ReadLine();
Console.WriteLine("输入密码");
string pwd = Console.ReadLine();
if (name=="xiaotang"&&pwd.Equals("222"))
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}
Console.ReadKey();
字符串大小写转换
//大小写转换
string str = "lean C# C#";
Console.WriteLine(str.ToUpper());//大写
Console.WriteLine(str.ToLower());//小写
Console.ReadKey();
格式化字符串
//格式化符号c/d
Console.WriteLine(string.Format("货币哦{0:c}", 123));
Console.WriteLine(string.Format("分格符显示{0:n0}",123000));
Console.WriteLine("百分号显示{0:p0},{1:p0}",0.01,0.09);
Console.ReadKey();
截取字符串
//截取字符串
string str = "Program.cs";
string str1 = str.Substring(0, str.IndexOf('.'));
Console.WriteLine("文件名"+str1);
string str2=str.Substring(str.IndexOf("."));
Console.WriteLine(str2);
Console.ReadKey();
分割字符串
string str = "c#,java,javascript";
char[] arr = { ',' };
string[] str1= str.Split(arr,StringSplitOptions.RemoveEmptyEntries);
for (int i = 0;i < str1.Length; i++)
{
Console.WriteLine(str1[i]);
}
Console.ReadKey();
去除空白内容
//trim()
string str = " c# ";
string str1=str.Trim();
Console.WriteLine(str1);
Console.WriteLine(str);
Console.ReadKey();
替换字符串
//替换字符串replace
string str = "java nice";
Console.WriteLine(str);
string str1 = str.Replace('j', '#');
Console.WriteLine(str1);
string str2 = str.Replace("java", "c#");
Console.WriteLine(str2);
Console.ReadKey();
可变字符串
StringBuilder
//stringbulider可变字符序列
//Append将文本追加到对象末尾
//AppendFormat自定义的值加到对象末尾
//Insert将字符串加到对象指定位置
//Remove从对象中移除指定字符
//Replace用另一个字符替换对象内字符
int num = 111;
StringBuilder arr1 = new StringBuilder("c#最好");
arr1.Append("nice");
Console.WriteLine(arr1);//
arr1.AppendFormat("{0:c0}", num);
Console.WriteLine(arr1);//
arr1.Insert(0, "编程");
Console.WriteLine(arr1);//
arr1.Remove(5,arr1.Length-5);
Console.WriteLine(arr1);//
arr1.Replace("编程", "计算机");
Console.WriteLine(arr1);//
Console.ReadKey();
stringBuilder和string的区别
//string每操作一次创建一个新对象,stringBuilder的每次操作是对自身对象进行操作
//当大量对字符串进行操作时,须使用stringBuilder,避免产生过多的对象