C#基础-字符串
字符串比较,strA.CompareTo(strB)
A大于B 正数
A小于B 负数
A等于B 0
string strA = "ab";
string strB = "jk";
int intResult = strA.CompareTo(strB);
Console.WriteLine(intResult);
查找字符串的位置
IndexOf,LastIndexOf,StartWith,EndWith
string str = "Hello world!";
int index = str.IndexOf('o');
int index = str.LastIndexOf('o');
int index = str.IndexOf("lo");
Console.WriteLine(index);
格式化输出
string strFormat = string.Format("位置1:{0},位置2:{1}", 1, 2);
Console.WriteLine(strFormat);
输出钱的格式
double dMoney = 35.342552;
string strMoney = string.Format("{0:c}", dMoney);
Console.WriteLine(strMoney); // c代表人民币,
Concat,Join,'+'表示连接字符串
string str1 = "Hello";
string str2 = "World";
string strNew = string.Concat(str1, str2);
Console.WriteLine("通过Concat输出结果:"+strNew);
string strNew2 = string.Join('-',str1, str2); //可以添加分隔符
Console.WriteLine("通过Join输出结果:"+strNew2);
string strNew3 = str1 + str2; //字符串拼接
Console.WriteLine("通过'+'输出结果:" + strNew3);
字符串拆分成字符串数组
string strTest = "Max--,Joe=,Kate";
string[] strArray = strTest.Split(new char[] { ',','-','='});
foreach(string str in strArray)
{
//清除输出为空格情况
if (!string.IsNullOrEmpty(str)) // 判断字符串是否为空
{
Console.WriteLine(str);
}
}
Trim清空字符串的空格,包括前导和后导
string str1 = " aaa ccc ddd ";
Console.WriteLine("字符串清空之前长度:"+str1.Length);
string str2 = str1.Trim();
Console.WriteLine("字符串清空之后长度:"+str2.Length);
Console.WriteLine(str2);
string str3 = str1.TrimStart();//清空前导
string str4 = str1.TrimEnd();//清空后导
Replace替换操作
string strH = "hello";
strH = strH.Replace('h', 'H');
Console.WriteLine("替换之后的字符串:" + strH);
ToUpper(),ToLower()字符串转换为大小写方法
string str = "aaannBBcc";
Console.WriteLine("字符串转换为大写为" + str.ToUpper()); // ToUpper()转化为大写
Console.WriteLine("字符串转换为小写为" + str.ToLower()); // ToLower()转化为小写
日期操作
DateTime dtime = DateTime.Now;
string strTime = dtime.ToString("yyyy年MM月dd日 HH时mm分ss秒");
Console.WriteLine(strTime);
DateTime dtime1 = DateTime.Now.AddDays(1); //明天
DateTime dtime2 = DateTime.Now.AddDays(-1); //昨天