字符串操作(大小写、去空格、拆分、替换、索引、判断首尾、比较、截取等)

1、大小写、去空格、拆分、替换:

string str = "  www.cnblog.com  ";//前后各2个空格
string res1 = str.ToLower();//转小写
string res2 = str.ToUpper();//转大写
string res3 = str.Trim();//去除前后空格
string res4 = str.TrimStart();//去除前空格
string res5 = str.TrimEnd();//去除后空格
string[] res6 = str.Split('.');//按.拆分成数组。('.',2)则拆分2次
string res7 = str.Replace('c', 'd');//将c替换为d
string res8 = str.Replace("com", "cn");//字符串替换

2、索引、判断字符串首尾

string str = "xixixing";
int i1=str.IndexOf('x');//第一次出现时的索引位置,i1=0。无则返回-1
int i2 = str.IndexOf('x',i1);//指定位置往后查询,第一次出现时的位置,i2=2
//str.LastIndexOf()同上
bool result = str.StartsWith("www"); //true,区分大小写
bool result1 = str.StartsWith("Www",true,null); //true,不区分大小写
//res3.EndsWith()同上

3、比较(长度比较,内容比较)

string str1 = "xixixing";
string str2 = "zuoyizhongguo";
int res=string.Compare(str1, str2);//长度的比较,大于1,等于0,小于-1
//int res = str1.CompareTo(str2); //同上等效
bool res1 = string.Equals(str1, str2);//内容的比较,区分大小写
//bool res1 = str1.Equals(str2); //同上等效

 4、字符串截取,如从身份证号中获得出生日期

string id = "012345199012010000";
string birthday=id.Substring(6, 8);//从索引6开始后的8位,19901201
//id.Substring(6);//[6,最终)