1:startswith 字符串以。。。开头
// startswith 字符串以。。。开头 string[] strArr = { "asd","azx","qwe","aser","asdfgh"}; for (int i = 0; i < strArr.Length; i++) { if(strArr[i].StartsWith("as")) { Console.WriteLine(strArr[i]); } }
2:endswith 字符串以。。。结尾
// endswith 字符串以。。。结尾 for (int i = 0; i < strArr.Length; i++) { if(strArr[i].EndsWith("d")) { Console.WriteLine(strArr[i]); } }
3:IndexOf 查找第一次在字符串中出现的位置(字符串,找到那)如果找不到,返回-1
// IndexOf 查找第一次在字符串中出现的位置(字符串,从哪里开始找) string str = "hello world"; int index = str.IndexOf("ll",0); Console.WriteLine(index);
4:IndexOfAny 同时搜索多个字符串,直到找到其中一个位置
char[] rest = { 'o', 'l' }; int xx = str.IndexOfAny(rest); Console.WriteLine(xx);
5:截取字符串substring (从那开始,截取几位)
string a = str.Substring(4); string b = str.Substring(4,6); Console.WriteLine(a); Console.WriteLine(b);
6:拆分字符串 split 变成数组
string[] sd = str.Split(' '); for (int i = 0; i < sd.Length; i++) { Console.WriteLine(sd[i]); }
7:ToUpper/ToLower 字符串转为大写
// 字符串转大小写 string az = "ASDasdfg"; string q = az.ToUpper(); Console.WriteLine(q); string w = az.ToLower(); Console.WriteLine(w);
8:修改字符串 insert replace remove
Insert(从第几位插入,插入元素);
Replace(替换元素,换成啥)
Remove(从第几位开始,删几位)
string kk = "I Love You"; string sx = kk.Insert(3,"s"); Console.WriteLine(sx); string sc = kk.Replace("s"," "); Console.WriteLine(sc); string sv = kk.Remove(2,4); Console.WriteLine(sv);
9:Trim 去除两端字符串空格(TrimEnd,TrimStart)
string asd = " qwe "; string asa = asd.Trim(); Console.WriteLine(asa);
10:字符串对比
(1):str1 == str2
string str1 = "123"; string str2 = "234"; if (str1 == str2) { Console.WriteLine("true"); } else { Console.WriteLine("false"); }
(2):Equals
// Equals if (str1.Equals(str2)) { Console.WriteLine(true); } else { Console.WriteLine(false); }
(3):Equals
if (Equals(str1, str2)) { Console.WriteLine(true); } else { Console.WriteLine(false); }
11:PadLeft()、 PadRight() 在字串左(或右)加空格或指定char字符,使字串达到指定长度。(字符串的长度,以什么字符补充)
string str3 = "中偶人"; string str4 = str3.PadRight(10,'2'); Console.WriteLine(str4);