一、字符数组转换为字符串→char[]转string
char[] charArray = {'a','b','c','d'};
string str = new string(charArray);
Console.WriteLine(str);
Console.ReadKey();
输出结果:abcd;
二、获得字符串的长度
string number = "1234 5678";
int size = number.Length;
Console.WriteLine(size);
Console.ReadKey();
输出结果:9
注意:length属性返回的字符串长度是包括字符串中空格
三、获取指定位置的字符
string str = "努力工作是人生最好的投资";
char chr = str[5];
Console.WriteLine(chr);
Console.ReadKey();
输出结果:人
注意:字符串中的索引位置是从0开始的
四、获取字符串索引位置/判断字符串是否包含某个特定的字符
string str = "we are the world";
int size = str.IndexOf("e"); //区分大小写
Console.WriteLine(size);
Console.ReadKey();
输出结果:1
注意:如果找到特定字符,返回从零开始的索引,未找到返回-1
index方法有多个重载,更多用法请参考相关资料
扩展1:不区分大小写
string str = "we are the world";
int size = str.IndexOf("TH",StringComparison.CurrentCultureIgnoreCase);//比较时忽略大小写
Console.WriteLine(size); //返回比较的字符在字符串中第一次出现的索引位置 输出结果:7
扩展2:区分大小写
string str = "we are the world";
bool b = str.Contains("TH"); //比较时区分大小写,返回true为包含,false不包含
Console.WriteLine(b); //输出结果:false
扩展3:查找第2次出现的位置(不区分大小写)
string str = "we are the world th";
int firstIndex = str.IndexOf("TH", StringComparison.CurrentCultureIgnoreCase);
Console.WriteLine(firstIndex); // 第1次查找结果 输出:7
int secondIndex = str.IndexOf("TH", firstIndex + 1, StringComparison.CurrentCultureIgnoreCase);
Console.WriteLine(secondIndex); //第2次查找结果 输出:17
五、判断字符串首尾内容
string类提供了两种判断字符串首尾内容的方法,即startswith和endswith方法。其中startswith方法用来判断字符串是否以指定的内容开始,而endswith用来判断字符串是否以指定的字符结束
string str = "梦想还是要有的,万一实现了呢!";
bool result = str.StartsWith("梦想");
Console.WriteLine(result);
Console.ReadKey();
输出结果:TRUE
注意:如果是返回true,不是返回false
startswith方法有多个重载,如果在判断字符时,不区分大小写,请参考相关资料
六、字符串的大小写转换
大写:ToUpper()
小写:ToLower()
string str = "Learn and Live";
Console.WriteLine(str.ToUpper()) ;
Console.WriteLine(str.ToLower());
Console.ReadKey();
输出:
LEARN AND LIVE
learn and live
七、截取字符串(substring)
string str = "好好学习,天天向上";
Console.WriteLine(str.Substring(2,1));
Console.ReadKey();
输出:学
八、分割字符串(Split)
string str = "老当益壮,宁移白首之心,穷且益坚,不坠青云之志";
char[] separator = { ',' };
string[] splitstring = str.Split(separator,StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < splitstring.Length; i++)
{
Console.WriteLine(splitstring[i]);
}
Console.ReadKey();
输出结果:
老当益壮
宁移白首之心
穷且益坚
不坠青云之志
九、去掉字符串中的空格
string str = " Hello World ";
string trimmedStr = str.Replace(" ", "");
Console.WriteLine(trimmedStr); // 输出:HelloWorld
string str = "Hello\r\nWorld!";
string result = str.Replace("\r\n", "");
Console.WriteLine(result); // 输出:HelloWorld!